Gallery · Data analysis

Three species of penguin, one PowerShell DataFrame

PowerShell downloads the Palmer Penguins CSV, types it as a Microsoft.Data.Analysis DataFrame, and groups it by species, with every table drawn by Verso's DataFrame formatter. Three Vega-Lite charts follow, each a spec built as a PowerShell hashtable, and one of them quietly disagrees with the DataFrame about the average.

palmer-penguins.verso PowerShell · 18 cells Read-only preview Download

Three species of penguin, one PowerShell DataFrame

The Palmer Penguins are the friendlier successor to the iris flowers: 344 birds from three islands off the Antarctic Peninsula, each with a bill, a flipper and a weight on record, and two of them with nothing on record at all. This notebook takes them through PowerShell, a language nobody reaches for to do data analysis, and finds it does not need to be one. The DataFrame module puts Microsoft.Data.Analysis behind cmdlets, Verso draws every frame as a table, and Vega-Lite turns three hashtables into three charts.

Everything below is baked from a real run: the code computed it, the page just remembers.

What it needs

The DataFrame module comes from the PowerShell Gallery and has to be there before Verso starts, installed from an ordinary PowerShell prompt:

Install-Module DataFrame -Scope CurrentUser

The first cell fetches the CSV from the palmerpenguins repository and each chart fetches Vega-Lite from a CDN, so a run needs the network. Nothing is written to disk.

[1]
codePowerShell
1$module = Get-Module -ListAvailable -Name DataFrame |
2 Sort-Object Version -Descending |
3 Select-Object -First 1
4
5if (-not $module) {
6 throw 'The DataFrame module is required. Install it from a regular PowerShell terminal with: Install-Module DataFrame -Scope CurrentUser'
7}
8
9Import-Module $module.Path -Force
10
11$url = 'https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv'
12$csv = (Invoke-WebRequest -Uri $url).Content
13
14"Downloaded $($csv.Length) characters from the Palmer Penguins dataset."
✓completed
Downloaded 15241 characters from the Palmer Penguins dataset.

From text to typed columns

The file spells a missing value NA. Microsoft.Data.Analysis reads an empty field as null but a literal NA as a word, which would turn every measurement column into strings, so one regular expression blanks them out before import and the explicit column types keep the numbers numeric. Head(10) is the first look, and it arrives as a table rather than a property dump because Verso's DataFrame formatter knows the type. The fourth row is a bird that was tagged and never measured.

[2]
codePowerShell
1$cleanCsv = $csv -replace '(?m)(^|,)NA(?=,|$)', '$1'
2
3$columnTypes = @(
4 [string], # species
5 [string], # island
6 [double], # bill_length_mm
7 [double], # bill_depth_mm
8 [int], # flipper_length_mm
9 [int], # body_mass_g
10 [string], # sex
11 [int] # year
12)
13
14$penguins = Import-DataFrame `
15 -String $cleanCsv `
16 -ColumnType $columnTypes
17
18$penguins.Head(10)
✓completed
speciesStringislandStringbill_length_mmDoublebill_depth_mmDoubleflipper_length_mmInt32body_mass_gInt32sexStringyearInt32
AdelieTorgersen39.118.71813750male2007
AdelieTorgersen39.517.41863800female2007
AdelieTorgersen40.3181953250female2007
AdelieTorgersennullnullnullnull2007
AdelieTorgersen36.719.31933450female2007
AdelieTorgersen39.320.61903650male2007
AdelieTorgersen38.917.81813625female2007
AdelieTorgersen39.219.61954675male2007
AdelieTorgersen34.118.119334752007
AdelieTorgersen4220.219042502007

What 344 rows look like

A DataFrame is one object, so its shape is two property reads. Info() gives each column's type and its count of values that are not null, which is where the two unmeasured birds show up as 342 against 344. Description() puts a range on the measurements: body mass runs from 2,700 to 6,300 grams, and the average bird weighs a little over four kilograms.

[3]
codePowerShell
1"Rows: $($penguins.Rows.Count)"
2"Columns: $($penguins.Columns.Count)"
3
4$penguins.Info()
5$penguins.Description()
✓completed
Rows: 344
Columns: 8
InfoStringspeciesStringislandStringbill_length_mmStringbill_depth_mmStringflipper_length_mmStringbody_mass_gStringsexStringyearString
DataTypeSystem.StringSystem.StringSystem.DoubleSystem.DoubleSystem.Int32System.Int32System.StringSystem.Int32
Length (excluding null values)344344342342342342344344
DescriptionStringbill_length_mmSinglebill_depth_mmSingleflipper_length_mmSinglebody_mass_gSingleyearSingle
Length (excluding null values)342342342342344
Max59.621.523163002009
Min32.113.117227002007
Mean43.6665717.051455199.747094177.32572008.029

Grouped without leaving the frame

GroupBy and Mean run inside the DataFrame API rather than through Group-Object, so the result is another DataFrame and it renders the same way. Gentoo come out more than a kilogram heavier than either of the other two. Keep these figures in mind for the bar chart further down, which disagrees with them slightly, and for a reason.

[4]
codePowerShell
1$massBySpecies = $penguins.
2 GroupBy('species').
3 Mean('body_mass_g')
4
5$massBySpecies
✓completed
speciesStringbody_mass_gDouble
Adelie3676.315789473684
Gentoo5035.080645161291
Chinstrap3733.0882352941176

Charts from hashtables

Vega-Lite is a JSON grammar, and a PowerShell hashtable is a JSON object that has not been serialized yet. Show-VegaLite does the serializing, wraps the spec in a self-contained HTML document with pinned Vega, Vega-Lite and Vega-Embed builds, and hands it to Verso as a widget, which draws it in a frame of its own. Base64 keeps a spec full of quotes and braces from ever meeting the surrounding markup.

codePowerShell
1function Show-VegaLite {
2 param(
3 [Parameter(Mandatory)]
4 $Spec
5 )
6
7 $specJson = $Spec | ConvertTo-Json -Depth 100 -Compress
8 $specBase64 = [Convert]::ToBase64String(
9 [Text.Encoding]::UTF8.GetBytes($specJson)
10 )
11
12 $document = @"
13<!doctype html>
14<html>
15<head>
16 <meta charset="utf-8">
17 <script src="https://cdn.jsdelivr.net/npm/vega@6.3.1"></script>
18 <script src="https://cdn.jsdelivr.net/npm/vega-lite@6.4.3"></script>
19 <script src="https://cdn.jsdelivr.net/npm/vega-embed@7.1.0"></script>
20 <style>
21 html, body {
22 margin: 0;
23 padding: 0;
24 background: var(--verso-cell-output-background, white);
25 color: var(--verso-cell-output-foreground, #1e1e1e);
26 font-family: var(--verso-ui-font-family, sans-serif);
27 }
28 #vis { width: 100%; }
29 .error { padding: 12px; color: #c62828; white-space: pre-wrap; }
30 </style>
31</head>
32<body>
33 <div id="vis"></div>
34 <script>
35 const binary = atob("$specBase64");
36 const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
37 const spec = JSON.parse(new TextDecoder().decode(bytes));
38
39 vegaEmbed("#vis", spec, { renderer: "svg", actions: true })
40 .catch(error => {
41 document.body.innerHTML = '<div class="error"></div>';
42 document.querySelector(".error").textContent = error.stack || error.message;
43 });
44 </script>
45</body>
46</html>
47"@
48
49 $document | Display -MimeType 'text/x-verso-widget'
50}

Bill against flipper

Three species, three clouds. Gentoo sit apart on both axes; Adelie and Chinstrap overlap on flipper length and separate on bill length; the marker shape is the bird's sex. Hover a point for the rest of its row. The spec parses the CSV string itself, so the chart is reading the same download the DataFrame did.

[5]
codePowerShell
1$scatterSpec = [ordered]@{
2 '$schema' = 'https://vega.github.io/schema/vega-lite/v6.json'
3 title = 'Penguin bill length vs. flipper length'
4 width = 'container'
5 height = 420
6 data = @{
7 values = $csv
8 format = @{
9 type = 'csv'
10 parse = @{
11 bill_length_mm = 'number'
12 bill_depth_mm = 'number'
13 flipper_length_mm = 'number'
14 body_mass_g = 'number'
15 year = 'number'
16 }
17 }
18 }
19 transform = @(
20 @{ filter = 'isValid(datum.bill_length_mm) && isValid(datum.flipper_length_mm)' }
21 )
22 mark = @{ type = 'point'; filled = $true; size = 85; opacity = 0.75 }
23 encoding = @{
24 x = @{
25 field = 'bill_length_mm'; type = 'quantitative'; title = 'Bill length (mm)'
26 scale = @{ zero = $false }
27 }
28 y = @{
29 field = 'flipper_length_mm'; type = 'quantitative'; title = 'Flipper length (mm)'
30 scale = @{ zero = $false }
31 }
32 color = @{ field = 'species'; type = 'nominal'; title = 'Species' }
33 shape = @{ field = 'sex'; type = 'nominal'; title = 'Sex' }
34 tooltip = @(
35 @{ field = 'species'; type = 'nominal'; title = 'Species' }
36 @{ field = 'island'; type = 'nominal'; title = 'Island' }
37 @{ field = 'sex'; type = 'nominal'; title = 'Sex' }
38 @{ field = 'bill_length_mm'; type = 'quantitative'; title = 'Bill length' }
39 @{ field = 'flipper_length_mm'; type = 'quantitative'; title = 'Flipper length' }
40 @{ field = 'body_mass_g'; type = 'quantitative'; title = 'Body mass' }
41 )
42 }
43}
44
45Show-VegaLite $scatterSpec
✓completed

The average, by a second engine

Vega-Lite aggregates as it draws, so mean is written into the encoding rather than computed first, and the bars sort themselves by value. Hover one and the figure is not the one the DataFrame gave: Adelie and Gentoo each come out a few dozen grams heavier here. The difference is exactly one bird per group. The chart's filter drops the two penguins with no weight before averaging, while Mean on the DataFrame keeps them in the denominator. Same data, two engines, and the one that filtered first is the one to trust.

[6]
codePowerShell
1$barSpec = [ordered]@{
2 '$schema' = 'https://vega.github.io/schema/vega-lite/v6.json'
3 title = 'Average body mass by species'
4 width = 'container'
5 height = 360
6 data = @{
7 values = $csv
8 format = @{ type = 'csv'; parse = @{ body_mass_g = 'number' } }
9 }
10 transform = @(
11 @{ filter = 'isValid(datum.body_mass_g)' }
12 )
13 mark = @{ type = 'bar'; cornerRadius = 3 }
14 encoding = @{
15 x = @{ field = 'species'; type = 'nominal'; title = 'Species'; sort = '-y' }
16 y = @{
17 field = 'body_mass_g'; type = 'quantitative'; aggregate = 'mean'
18 title = 'Average body mass (g)'
19 }
20 color = @{ field = 'species'; type = 'nominal'; legend = $null }
21 tooltip = @(
22 @{ field = 'species'; type = 'nominal'; title = 'Species' }
23 @{
24 field = 'body_mass_g'; type = 'quantitative'; aggregate = 'mean'
25 title = 'Average mass'; format = '.0f'
26 }
27 )
28 }
29}
30
31Show-VegaLite $barSpec
✓completed

Every bird, binned

Faceting gives each species a histogram of its own on shared axes, so the panels read against each other. Gentoo are heavier across the whole distribution, not just on average, and Adelie and Chinstrap are close to the same bird by weight.

[7]
codePowerShell
1$histogramSpec = [ordered]@{
2 '$schema' = 'https://vega.github.io/schema/vega-lite/v6.json'
3 title = 'Body mass distribution by species'
4 data = @{
5 values = $csv
6 format = @{ type = 'csv'; parse = @{ body_mass_g = 'number' } }
7 }
8 transform = @(
9 @{ filter = 'isValid(datum.body_mass_g)' }
10 )
11 facet = @{
12 column = @{ field = 'species'; type = 'nominal'; title = $null }
13 }
14 spec = @{
15 width = 220
16 height = 280
17 mark = @{ type = 'bar'; cornerRadius = 2 }
18 encoding = @{
19 x = @{
20 field = 'body_mass_g'; type = 'quantitative'; title = 'Body mass (g)'
21 bin = @{ maxbins = 20 }
22 }
23 y = @{ aggregate = 'count'; type = 'quantitative'; title = 'Number of penguins' }
24 color = @{ field = 'species'; type = 'nominal'; legend = $null }
25 tooltip = @(
26 @{ field = 'body_mass_g'; type = 'quantitative'; bin = $true; title = 'Body mass range' }
27 @{ aggregate = 'count'; type = 'quantitative'; title = 'Penguins' }
28 )
29 }
30 }
31 resolve = @{ scale = @{ x = 'shared'; y = 'shared' } }
32}
33
34Show-VegaLite $histogramSpec
✓completed

Take it home

Download the notebook from the gallery page and open it in VS Code with the Verso extension, or serve it with verso serve palmer-penguins.verso, with the DataFrame module installed first. Swap every body_mass_g in the histogram spec for bill_depth_mm and rerun the cell: the heaviest birds turn out to have the shallowest bills.

Run it yourself

Nothing on this page is executable; the outputs were baked in by a real run. Download the notebook and it runs anywhere Verso does: VS Code, the browser, or the terminal.

dotnet tool install --global Verso.Cli
verso serve palmer-penguins.verso

What this shows

PowerShell downloads the Palmer Penguins CSV, types it as a Microsoft.Data.Analysis DataFrame, and groups it by species, with every table drawn by Verso's DataFrame formatter. Three Vega-Lite charts follow, each a spec built as a PowerShell hashtable, and one of them quietly disagrees with the DataFrame about the average.

Every language in this notebook reads and writes the same variable store, so a value produced in one cell is simply there in the next, whatever the language.