Examples

These are the tables of the Great Tables Examples page, from a small table of the largest landmasses to a year of sales of coffee equipment with icons and bar plots.

import std/streams
import nanuq
import tabelline, tabelline/nanuq, gtdata

let islandsMini = readCsv(newStringStream(islandsCsv))
  .sort("size", descending = true)
  .head(10)

let islandsTbl = tabella(islandsMini):
  tabHeader "Large Landmasses of the World", "The top ten largest are presented"
  tabStub "name"
  tabSourceNote "Source: The World Almanac and Book of Facts, 1975, page 406."
  tabSourceNote md"Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley."
  tabStubhead "landmass"
  fmtInteger "size"
nbTable islandsTbl
Large Landmasses of the World
The top ten largest are presented
landmasssize
Asia16,988
Africa11,506
North America9,390
South America6,795
Antarctica5,500
Europe3,745
Australia2,968
Greenland840
New Guinea306
Borneo280
Source: The World Almanac and Book of Facts, 1975, page 406.
Reference: McNeil, D. R. (1977) Interactive Data Analysis. Wiley.
let airqualityMini = readCsv(newStringStream(airqualityCsv), inferSchemaLength = 10_000)
  .head(10)
  .withColumns(lit(1973).alias("Year"))

let airqualityTbl = tabella(airqualityMini):
  tabHeader "New York Air Quality Measurements",
    "Daily measurements in New York City (May 1-10, 1973)"
  tabSpanner "Time", ["Year", "Month", "Day"]
  tabSpanner "Measurement", ["Ozone", "Solar_R", "Wind", "Temp"]
  colsMoveToStart ["Year", "Month", "Day"]
  colsLabel:
    Ozone: html"Ozone,<br>ppbV"
    Solar_R: html"Solar R.,<br>cal/m<sup>2</sup>"
    Wind: html"Wind,<br>mph"
    Temp: html"Temp,<br>&deg;F"
nbTable airqualityTbl
New York Air Quality Measurements
Daily measurements in New York City (May 1-10, 1973)
TimeMeasurement
YearMonthDayOzone,
ppbV
Solar R.,
cal/m2
Wind,
mph
Temp,
°F
197351411907.467
197352361188.072
1973531214912.674
1973541831311.562
197355NANA14.356
19735628NA14.966
197357232998.665
197358199913.859
19735981920.161
1973510NA1948.669
import std/[sequtils, tables]

# Get lists of 2-letter country codes for each region of Oceania
let oceania = {
  "Australasia": @["AU", "NZ"],
  "Melanesia": @["NC", "PG", "SB", "VU"],
  "Micronesia": @["FM", "GU", "KI", "MH", "MP", "NR", "PW"],
  "Polynesia": @["PF", "WS", "TO", "TV"]}.toOrderedTable

# Create a table mapping country to region (e.g. AU -> Australasia)
var countryToRegion = initOrderedTable[string, string]()
for region, countries in oceania:
  for country in countries: countryToRegion[country] = region

var codes: seq[string]
for country in countryToRegion.keys: codes.add country

let widePops = readCsv(newStringStream(countrypopsCsv), inferSchemaLength = 10_000)
  .filter(col("country_code_2").isIn(codes) and col("year").isIn([2000, 2010, 2020]))
  .withColumns(col("country_code_2").replace(countryToRegion.pairs.toSeq).alias("region"))
  .pivot(index = ["country_name", "region"], on = "year", values = "population")
  .sort("2020", descending = true)

let widePopsTbl = tabella(widePops, rownameCol = "country_name", groupnameCol = "region"):
  tabHeader "Populations of Oceania's Countries in 2000, 2010, and 2020"
  tabSpanner "Total Population", everything()
  fmtInteger()
nbTable widePopsTbl
Populations of Oceania's Countries in 2000, 2010, and 2020
Total Population
200020102020
Australasia
Australia19,028,80222,031,75025,655,289
New Zealand3,857,7004,350,7005,090,200
Melanesia
Papua New Guinea5,508,2977,583,2699,749,640
Solomon Islands429,978540,394691,191
Vanuatu192,074245,453311,685
New Caledonia213,230249,750272,460
Polynesia
French Polynesia250,927283,788301,920
Samoa184,008194,672214,929
Tonga102,603107,383105,254
Tuvalu9,63810,55011,069
Micronesia
Guam160,188164,905169,231
Kiribati88,826107,995126,463
Micronesia (Federated States)111,709107,588112,106
Northern Mariana Islands80,33854,08749,587
Marshall Islands54,22453,41643,413
Palau19,72618,54017,972
Nauru10,37710,24112,315
let townyMini = readCsv(newStringStream(townyCsv), inferSchemaLength = 10_000)
  .select("name", "website", "density_2021", "land_area_km2", "latitude", "longitude")
  .sort("density_2021", descending = true)
  .head(10)
  .withColumns(
    concatStr([lit("["), col("name"), lit("]("), col("website"), lit(")")]).alias("url_name"),
    concatStr([lit("[map](http://maps.google.com/?ie=UTF8&hq=&ll="),
               col("latitude").`cast`(String), lit(","), col("longitude").`cast`(String),
               lit("&z=13)")]).alias("location"))
  .select("url_name", "location", "land_area_km2", "density_2021")

let townyTbl = tabella(townyMini, rownameCol = "url_name"):
  tabHeader "The Municipalities of Ontario", "The top 10 highest population density in 2021"
  tabStubhead "Municipality"
  fmtMarkdown ["url_name", "location"]
  fmtNumber ["land_area_km2", "density_2021"], decimals = 1
  colsLabel:
    land_area_km2: html"land area, <br>km<sup>2</sup>"
    density_2021: html"density, <br>people/km<sup>2</sup>"
nbTable townyTbl
The Municipalities of Ontario
The top 10 highest population density in 2021
Municipalitylocationland area,
km2
density,
people/km2
Torontomap631.14,427.8
Bramptonmap265.92,469.0
Mississaugamap292.72,452.6
Newmarketmap38.52,284.2
Richmond Hillmap100.82,004.4
Orangevillemap15.21,989.9
Ajaxmap66.61,900.8
Waterloomap64.11,895.7
Kitchenermap136.81,877.7
Guelphmap87.41,644.1
let szaPivot = readCsv(newStringStream(szaCsv), inferSchemaLength = 0)  # every column as text
  .filter(col("latitude") == "20" and col("tst") <= lit("1200"))
  .drop("latitude")
  .dropNulls()
  .withColumns(col("sza").`cast`(Float64))
  .pivot(values = "sza", index = "month", on = "tst", sortColumns = true)

let szaTbl = tabella(szaPivot, rownameCol = "month"):
  dataColor domain = (90.0, 0.0), palette = @["rebeccapurple", "white", "orange"],
    naColor = "white"
  tabHeader "Solar Zenith Angles from 05:30 to 12:00",
    html"Average monthly values at latitude of 20&deg;N."
  subMissing(missingText = "")
nbTable szaTbl
Solar Zenith Angles from 05:30 to 12:00
Average monthly values at latitude of 20°N.
05300600063007000730080008300900093010001030110011301200
jan84.978.772.766.161.556.552.148.345.543.643.0
feb88.982.575.869.663.357.752.247.443.140.037.837.2
mar85.778.872.065.258.652.346.240.535.531.428.627.7
apr88.581.574.467.460.353.446.539.733.226.921.317.215.5
may85.078.271.264.357.250.243.236.129.126.115.28.85.0
jun89.282.776.069.362.555.748.841.935.028.121.114.27.32.0
jul88.882.375.769.162.355.548.741.835.028.121.214.37.73.1
aug83.877.170.263.356.449.442.435.428.321.314.37.31.9
sep87.280.273.266.159.152.145.138.131.324.718.613.711.6
oct84.177.170.263.356.549.943.537.532.027.424.323.1
nov87.881.374.568.361.856.050.245.340.737.435.134.4
dec84.378.071.866.160.555.650.947.244.242.441.8

The Sports earnings example, the highest paid athletes of 2023, has a page of its own.

The next example is the carbon intensity of electricity consumption, by Grant Chalmers (source, blog post with the R code).

let powerCie = readCsv(newStringStream(powerCieCsv), inferSchemaLength = 10_000)

let widths = powerCie.columns[1 .. ^1].mapIt((it, "58px"))  # every column but Zone
let shares = ["Hydro", "Nuclear", "Wind", "Solar", "Geothermal", "Biomass", "Gas", "Coal",
              "Oil", "Unknown", "Hydro Discharge", "Battery Discharge"]

let powerTbl = tabella(powerCie):
  fmtPercent shares, decimals = 1
  fmtNumber "CO2 Intensity", decimals = 0
  dataColor "CO2 Intensity", domain = (0.0, 900.0), palette = @["#00A600", "#E6E600",
    "#E8C32E", "#D69C4E", "#Dc863B", "sienna", "sienna4", "tomato4", "brown"]
  dataColor ["Hydro", "Nuclear", "Wind", "Solar", "Geothermal"], domain = (0.0, 1.0),
    palette = @["snow", "chartreuse4", "chartreuse3", "#00A600"]
  dataColor "Biomass", domain = (0.0, 0.3), palette = @["snow", "#EEC900", "#E8C32E", "#D69C4E"]
  dataColor ["Gas", "Coal", "Oil"], domain = (0.0, 1.0),
    palette = @["snow", "#Dc863B", "#D69C4E", "sienna4", "tomato4"]
  dataColor ["Zone", "Unknown", "Hydro Discharge", "Battery Discharge"],
    palette = @["snow", "snow", "snow", "snow"]
  colsWidth widths
  tabHeader md"2023 Mean **Carbon Intensity** (gCO2eq/kWh) and **Power Consumption** Breakdown (%)"
  tabSourceNote md("**Source**: api.electricitymap.org" &
    " | **Methodology**: https://www.electricitymaps.com/methodology." &
    " Some emissions factors are based on IPCC 2014 defaults, while some are based on more accurate regional factors." &
    "<br>All zones are publicly available on the *Carbon intensity and emission factors* tab via Google docs link")
  optTableFont systemFonts("humanist")
  tabOptions(sourceNotesFontSize = "x-small", sourceNotesPadding = "3px",
             dataRowPadding = "1px", headingBackgroundColor = "antiquewhite",
             sourceNotesBackgroundColor = "antiquewhite",
             columnLabelsBackgroundColor = "antiquewhite", tableBackgroundColor = "snow",
             dataRowPaddingHorizontal = "3px", columnLabelsPaddingHorizontal = "58px")
  colsAlign alCenter
  colsAlign alLeft, "Zone"
  optTableOutline()
nbTable powerTbl
2023 Mean Carbon Intensity (gCO2eq/kWh) and Power Consumption Breakdown (%)
ZoneCO2 IntensityHydroNuclearWindSolarGeothermalBiomassGasCoalOilUnknownHydro DischargeBattery Discharge
Sweden2639.1%26.8%27.7%0.1%0.0%0.4%0.4%0.8%0.0%4.6%0.1%0.0%
Iceland2869.4%0.0%0.0%0.0%30.6%0.0%0.0%0.0%0.0%0.0%0.0%0.0%
Quebec3590.1%2.1%4.4%0.0%0.0%1.9%1.4%0.0%0.0%0.0%0.0%0.0%
France4612.3%65.4%10.3%1.8%0.0%1.0%7.1%0.3%0.3%0.1%1.4%0.0%
Ontario10423.3%49.4%8.7%0.1%0.0%0.2%18.1%0.0%0.0%0.0%0.0%0.0%
New Zealand10660.5%0.0%7.7%0.1%19.0%0.0%6.8%3.7%0.0%2.2%0.0%0.0%
Finland10720.2%36.5%24.1%0.1%0.0%6.2%3.0%8.1%0.0%1.8%0.0%0.0%
South Australia1320.7%0.0%42.6%33.7%0.0%0.0%13.3%9.0%0.0%0.0%0.0%0.7%
Spain13217.1%24.2%25.1%8.0%0.0%2.0%18.8%1.3%0.2%0.3%3.0%0.0%
Belgium1471.3%39.6%25.2%3.6%0.0%2.8%19.4%1.7%0.1%4.9%1.2%0.0%
Tasmania16249.0%0.0%22.6%10.8%0.0%0.0%1.5%16.1%0.0%0.0%0.0%0.0%
East Denmark1846.4%5.5%48.4%1.3%0.0%16.8%7.7%10.8%1.4%1.4%0.4%0.0%
West Denmark1888.8%2.2%56.3%1.6%0.0%7.6%8.5%13.0%0.9%0.4%0.6%0.0%
Great Britain2143.8%12.4%35.9%2.7%0.0%6.2%35.1%2.0%0.0%1.0%1.0%0.0%
Netherlands2181.1%3.9%46.7%10.8%0.0%4.6%22.4%8.6%0.8%1.1%0.2%0.0%
New York ISO27523.7%22.8%4.9%0.0%0.0%0.1%46.9%0.0%0.0%1.6%0.0%0.0%
Italy (North)30722.7%14.5%3.9%2.9%0.2%3.1%38.4%1.5%0.2%9.3%3.3%0.0%
California3288.4%12.7%7.9%12.0%3.0%1.8%48.5%2.1%0.0%1.2%0.0%2.6%
Germany3894.4%2.8%39.7%3.3%0.0%8.7%14.4%23.3%0.6%0.6%2.1%0.0%
Ireland3893.7%0.8%38.5%0.2%0.0%2.5%42.4%9.7%2.0%0.1%0.1%0.0%
Western Australia4170.0%0.0%14.1%33.8%0.0%0.3%24.2%27.1%0.3%0.0%0.0%0.3%
Texas4320.0%9.1%22.3%6.0%0.0%0.0%46.1%16.1%0.0%0.4%0.0%0.0%
Alberta4471.9%0.0%12.4%1.1%0.0%2.5%70.7%7.2%0.0%4.1%0.0%0.0%
Victoria5083.9%0.0%17.5%19.0%0.0%0.0%0.3%59.1%0.0%0.0%0.0%0.2%
New South Wales5783.2%0.0%9.5%23.7%0.0%0.2%0.7%62.6%0.0%0.0%0.0%0.1%
Queensland6621.9%0.0%3.8%21.1%0.0%0.0%7.2%65.7%0.2%0.0%0.0%0.1%
South Africa6852.2%4.3%5.8%3.8%0.0%0.0%0.0%79.9%2.0%0.1%2.0%0.0%
India (North)6939.3%2.2%0.1%10.6%0.0%0.0%1.8%75.2%0.0%0.9%0.0%0.0%
Source: api.electricitymap.org | Methodology: https://www.electricitymaps.com/methodology. Some emissions factors are based on IPCC 2014 defaults, while some are based on more accurate regional factors.
All zones are publicly available on the Carbon intensity and emission factors tab via Google docs link

The last example is a year of sales of coffee equipment, by Michael Chow (source, notebook).

let coffeeSales = readNdjson(newStringStream(coffeeSalesNdjson))

let selRev = startsWith("revenue")
let selProf = startsWith("profit")

let coffeeTable = tabella(coffeeSales):
  tabHeader "Sales of Coffee Equipment"
  tabSpanner "Revenue", selRev
  tabSpanner "Profit", selProf
  colsLabel:
    revenue_dollars: "Amount"
    profit_dollars: "Amount"
    revenue_pct: "Percent"
    profit_pct: "Percent"
    monthly_sales: "Monthly Sales"
    icon: ""
    product: "Product"
  # formatting ----
  fmtNumber endsWith("dollars"), compact = true, pattern = "${x}", nSigfig = 3
  fmtPercent endsWith("pct"), decimals = 0
  # style ----
  tabStyle style.fill("aliceblue"), loc.body(cols = selRev)
  tabStyle style.fill("papayawhip"), loc.body(cols = selProf)
  tabStyle style.text(weight = "bold"), loc.body(rows = where(it["product"] == "Total"))
  fmtNanoplot "monthly_sales", plotType = "bar"
  fmtImage "icon", path = coffeeIcons
  subMissing(missingText = "")
nbTable coffeeTable
Sales of Coffee Equipment
ProductRevenueProfitMonthly Sales
AmountPercentAmountPercent
grinder.pngGrinder$905K3%$568K4%7650521494596613667748765686607594568751
moka-pot.pngMoka pot$2.05M7%$181K1%6.87K04.73K4.74K4.79K5.51K6.16K6.62K6.87K6.03K5.30K4.88K4.65K6.28K
cold-brew.pngCold brew$289K1%$242K2%2.70K02442494389811.77K2.70K2.61K2.35K1.74K896499244
filter.pngFilter$404K1%$70.0K0%2.74K02.07K1.81K1.84K2.12K2.25K2.63K2.56K2.37K2.16K2.19K2.07K2.74K
drip-machine.pngDrip machine$2.63M9%$1.37M9%2.58K02.14K1.62K1.97K2.10K2.58K2.46K2.34K2.32K2.05K1.97K1.84K2.33K
aeropress.pngAeroPress$2.60M9%$1.29M9%9.27K06.33K5.20K6.37K7.02K7.91K8.70K8.69K7.80K6.83K6.96K6.88K9.27K
pour-over.pngPour over$846K3%$365K2%2.18K01.56K1.29K1.51K1.69K1.94K2.18K2.14K1.86K1.72K1.81K1.60K2.17K
french-press.pngFrench press$1.11M4%$748K5%4.82K03.51K2.88K3.35K3.79K3.91K4.09K4.18K4.43K3.28K3.42K3.30K4.82K
cezve.pngCezve$2.51M9%$1.97M13%17.1K012.2K11.5K11.8K13.6K15.4K16.5K17.1K14.4K13.0K12.9K11.6K15.9K
chemex.pngChemex$3.14M11%$818K6%7.22K04.94K4.17K5.24K6.00K6.36K6.77K7.11K6.25K5.61K6.08K4.98K7.22K
scale.pngScale$3.80M13%$2.91M20%3.18K01.54K1.57K1.68K2.03K2.42K2.55K2.57K2.23K2.04K2.09K1.69K3.18K
kettle.pngKettle$756K3%$618K4%1.53K01.14K1.02K1.09K1.13K1.41K1.48K1.46K1.30K1.14K1.23K1.19K1.53K
espresso-machine.pngEspresso Machine$8.41M29%$3.64M25%2.58K06868406185982.15K5337979961.00K6688582.58K
Total$29.4M100%$14.8M100%
import tabbook
bookInit()

nbText: "# Examples"

attribution gtExample("Examples", "https://posit-dev.github.io/great-tables/examples/",
  "The examples are shown one after the other, with their code, where the original sets them " &
  "in a grid with the code folded; the data files are read from the book's folder; the Sports " &
  "earnings example has a page of its own, next, and the gt-extras example comes with the other " &
  "gt-extras pages.")

nbText: """
These are the tables of the Great Tables Examples page, from a small table of the largest
landmasses to a year of sales of coffee equipment with icons and bar plots.
"""

tabs """
import polars as pl
from great_tables import GT, md, html
from great_tables.data import islands

islands_mini = (
    pl.from_pandas(islands).sort("size", descending=True)
    .head(10)
)

(
    GT(islands_mini)
    .tab_header(
        title="Large Landmasses of the World",
        subtitle="The top ten largest are presented"
    )
    .tab_stub(rowname_col="name")
    .tab_source_note(source_note="Source: The World Almanac and Book of Facts, 1975, page 406.")
    .tab_source_note(
        source_note=md("Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley.")
    )
    .tab_stubhead(label="landmass")
    .fmt_integer(columns="size")
)
""", """
library(gt)
library(dplyr)
library(tidyr)

islands_mini <-
  tibble(name = names(islands), size = islands) |>
  arrange(desc(size)) |>
  slice_head(n = 10)

islands_mini |>
  gt(rowname_col = "name") |>
  tab_header(
    title = "Large Landmasses of the World",
    subtitle = "The top ten largest are presented"
  ) |>
  tab_source_note(source_note = "Source: The World Almanac and Book of Facts, 1975, page 406.") |>
  tab_source_note(
    source_note = md("Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley.")
  ) |>
  tab_stubhead(label = "landmass") |>
  fmt_integer(columns = size)
""":
  nbCode:
    import std/streams
    import nanuq
    import tabelline, tabelline/nanuq, gtdata

    let islandsMini = readCsv(newStringStream(islandsCsv))
      .sort("size", descending = true)
      .head(10)

    let islandsTbl = tabella(islandsMini):
      tabHeader "Large Landmasses of the World", "The top ten largest are presented"
      tabStub "name"
      tabSourceNote "Source: The World Almanac and Book of Facts, 1975, page 406."
      tabSourceNote md"Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley."
      tabStubhead "landmass"
      fmtInteger "size"
    nbTable islandsTbl

tabelline """
The data steps are written with [nanuq](https://github.com/pietroppeter/nanuq), Polars for Nim,
as the examples write them with Polars; `import tabelline/nanuq` lets `tabella` take its data
frames. `tabStub` chooses the stub, as Great Tables' `tab_stub`; gt names it when the table is
made, which tabelline does too, with `tabella(data, rownameCol = "name")`.
"""

tabs """
from great_tables import GT, html
from great_tables.data import airquality

airquality_mini = airquality.head(10).assign(Year = 1973)

(
    GT(airquality_mini)
    .tab_header(
        title="New York Air Quality Measurements",
        subtitle="Daily measurements in New York City (May 1-10, 1973)"
    )
    .tab_spanner(
        label="Time",
        columns=["Year", "Month", "Day"]
    )
    .tab_spanner(
        label="Measurement",
        columns=["Ozone", "Solar_R", "Wind", "Temp"]
    )
    .cols_move_to_start(columns=["Year", "Month", "Day"])
    .cols_label(
        Ozone = html("Ozone,<br>ppbV"),
        Solar_R = html("Solar R.,<br>cal/m<sup>2</sup>"),
        Wind = html("Wind,<br>mph"),
        Temp = html("Temp,<br>&deg;F")
    )
)
""", """
airquality_mini <- airquality |> head(10) |> mutate(Year = 1973L)

airquality_mini |>
  gt() |>
  tab_header(
    title = "New York Air Quality Measurements",
    subtitle = "Daily measurements in New York City (May 1-10, 1973)"
  ) |>
  tab_spanner(
    label = "Time",
    columns = c(Year, Month, Day)
  ) |>
  tab_spanner(
    label = "Measurement",
    columns = c(Ozone, Solar.R, Wind, Temp)
  ) |>
  cols_move_to_start(columns = c(Year, Month, Day)) |>
  cols_label(
    Ozone = html("Ozone,<br>ppbV"),
    Solar.R = html("Solar R.,<br>cal/m<sup>2</sup>"),
    Wind = html("Wind,<br>mph"),
    Temp = html("Temp,<br>&deg;F")
  )
""":
  nbCode:
    let airqualityMini = readCsv(newStringStream(airqualityCsv), inferSchemaLength = 10_000)
      .head(10)
      .withColumns(lit(1973).alias("Year"))

    let airqualityTbl = tabella(airqualityMini):
      tabHeader "New York Air Quality Measurements",
        "Daily measurements in New York City (May 1-10, 1973)"
      tabSpanner "Time", ["Year", "Month", "Day"]
      tabSpanner "Measurement", ["Ozone", "Solar_R", "Wind", "Temp"]
      colsMoveToStart ["Year", "Month", "Day"]
      colsLabel:
        Ozone: html"Ozone,<br>ppbV"
        Solar_R: html"Solar R.,<br>cal/m<sup>2</sup>"
        Wind: html"Wind,<br>mph"
        Temp: html"Temp,<br>&deg;F"
    nbTable airqualityTbl

tabs """
from great_tables import GT
from great_tables.data import countrypops
import polars as pl
import polars.selectors as cs

# Get vectors of 2-letter country codes for each region of Oceania
oceania = {
    "Australasia": ["AU", "NZ"],
    "Melanesia": ["NC", "PG", "SB", "VU"],
    "Micronesia": ["FM", "GU", "KI", "MH", "MP", "NR", "PW"],
    "Polynesia": ["PF", "WS", "TO", "TV"],
}

# Create a dictionary mapping country to region (e.g. AU -> Australasia)
country_to_region = {
    country: region for region, countries in oceania.items() for country in countries
}

wide_pops = (
    pl.from_pandas(countrypops)
    .filter(
        pl.col("country_code_2").is_in(list(country_to_region))
        & pl.col("year").is_in([2000, 2010, 2020])
    )
    .with_columns(pl.col("country_code_2").replace(country_to_region).alias("region"))
    .pivot(index=["country_name", "region"], on="year", values="population")
    .sort("2020", descending=True)
)

(
    GT(wide_pops)
    .tab_header(title="Populations of Oceania's Countries in 2000, 2010, and 2020")
    .tab_spanner(label="Total Population", columns=cs.all())
    .tab_stub(rowname_col="country_name", groupname_col="region")
    .fmt_integer()
)
""", """
# Get vectors of 2-letter country codes for each region of Oceania
oceania <- list(
  Australasia = c("AU", "NZ"),
  Melanesia = c("NC", "PG", "SB", "VU"),
  Micronesia = c("FM", "GU", "KI", "MH", "MP", "NR", "PW"),
  Polynesia = c("PF", "WS", "TO", "TV")
)

# A named vector mapping country to region (e.g. AU -> Australasia)
country_to_region <- setNames(rep(names(oceania), lengths(oceania)), unlist(oceania))

wide_pops <-
  countrypops |>
  filter(country_code_2 %in% names(country_to_region), year %in% c(2000, 2010, 2020)) |>
  mutate(region = country_to_region[country_code_2]) |>
  select(country_name, region, year, population) |>
  pivot_wider(names_from = year, values_from = population) |>
  arrange(desc(`2020`))

wide_pops |>
  gt(rowname_col = "country_name", groupname_col = "region") |>
  tab_header(title = "Populations of Oceania's Countries in 2000, 2010, and 2020") |>
  tab_spanner(label = "Total Population", columns = everything()) |>
  fmt_integer()
""":
  nbCode:
    import std/[sequtils, tables]

    # Get lists of 2-letter country codes for each region of Oceania
    let oceania = {
      "Australasia": @["AU", "NZ"],
      "Melanesia": @["NC", "PG", "SB", "VU"],
      "Micronesia": @["FM", "GU", "KI", "MH", "MP", "NR", "PW"],
      "Polynesia": @["PF", "WS", "TO", "TV"]}.toOrderedTable

    # Create a table mapping country to region (e.g. AU -> Australasia)
    var countryToRegion = initOrderedTable[string, string]()
    for region, countries in oceania:
      for country in countries: countryToRegion[country] = region

    var codes: seq[string]
    for country in countryToRegion.keys: codes.add country

    let widePops = readCsv(newStringStream(countrypopsCsv), inferSchemaLength = 10_000)
      .filter(col("country_code_2").isIn(codes) and col("year").isIn([2000, 2010, 2020]))
      .withColumns(col("country_code_2").replace(countryToRegion.pairs.toSeq).alias("region"))
      .pivot(index = ["country_name", "region"], on = "year", values = "population")
      .sort("2020", descending = true)

    let widePopsTbl = tabella(widePops, rownameCol = "country_name", groupnameCol = "region"):
      tabHeader "Populations of Oceania's Countries in 2000, 2010, and 2020"
      tabSpanner "Total Population", everything()
      fmtInteger()
    nbTable widePopsTbl

tabs """
from great_tables import GT, html
from great_tables.data import towny

towny_mini = (
    towny[["name", "website", "density_2021", "land_area_km2", "latitude", "longitude"]]
    .sort_values("density_2021", ascending=False)
    .head(10)
)

towny_mini["url_name"] = "[" + towny_mini["name"] + "](" + towny_mini["website"] + ")"

towny_mini["location"] = (
    "[map](http://maps.google.com/?ie=UTF8&hq=&ll="
    + towny_mini["latitude"].astype(str)
    + ","
    + towny_mini["longitude"].astype(str)
    + "&z=13)"
)

(
    GT(
        towny_mini[["url_name", "location", "land_area_km2", "density_2021"]],
        rowname_col="url_name",
    )
    .tab_header(
        title="The Municipalities of Ontario",
        subtitle="The top 10 highest population density in 2021",
    )
    .tab_stubhead(label="Municipality")
    .fmt_markdown(columns=["url_name", "location"])
    .fmt_number(columns=["land_area_km2", "density_2021"], decimals=1)
    .cols_label(
        land_area_km2=html("land area, <br>km<sup>2</sup>"),
        density_2021=html("density, <br>people/km<sup>2</sup>"),
    )
)
""", """
towny_mini <-
  towny |>
  select(name, website, density_2021, land_area_km2, latitude, longitude) |>
  arrange(desc(density_2021)) |>
  slice_head(n = 10) |>
  mutate(
    url_name = paste0("[", name, "](", website, ")"),
    location = paste0(
      "[map](http://maps.google.com/?ie=UTF8&hq=&ll=",
      latitude, ",", longitude, "&z=13)"
    )
  )

towny_mini |>
  select(url_name, location, land_area_km2, density_2021) |>
  gt(rowname_col = "url_name") |>
  tab_header(
    title = "The Municipalities of Ontario",
    subtitle = "The top 10 highest population density in 2021"
  ) |>
  tab_stubhead(label = "Municipality") |>
  fmt_markdown(columns = c(url_name, location)) |>
  fmt_number(columns = c(land_area_km2, density_2021), decimals = 1) |>
  cols_label(
    land_area_km2 = html("land area, <br>km<sup>2</sup>"),
    density_2021 = html("density, <br>people/km<sup>2</sup>")
  )
""":
  nbCode:
    let townyMini = readCsv(newStringStream(townyCsv), inferSchemaLength = 10_000)
      .select("name", "website", "density_2021", "land_area_km2", "latitude", "longitude")
      .sort("density_2021", descending = true)
      .head(10)
      .withColumns(
        concatStr([lit("["), col("name"), lit("]("), col("website"), lit(")")]).alias("url_name"),
        concatStr([lit("[map](http://maps.google.com/?ie=UTF8&hq=&ll="),
                   col("latitude").`cast`(String), lit(","), col("longitude").`cast`(String),
                   lit("&z=13)")]).alias("location"))
      .select("url_name", "location", "land_area_km2", "density_2021")

    let townyTbl = tabella(townyMini, rownameCol = "url_name"):
      tabHeader "The Municipalities of Ontario", "The top 10 highest population density in 2021"
      tabStubhead "Municipality"
      fmtMarkdown ["url_name", "location"]
      fmtNumber ["land_area_km2", "density_2021"], decimals = 1
      colsLabel:
        land_area_km2: html"land area, <br>km<sup>2</sup>"
        density_2021: html"density, <br>people/km<sup>2</sup>"
    nbTable townyTbl

tabs """
from great_tables import GT, html
from great_tables.data import sza
import polars as pl
import polars.selectors as cs

sza_pivot = (
    pl.from_pandas(sza)
    .filter((pl.col("latitude") == "20") & (pl.col("tst") <= "1200"))
    .select(pl.col("*").exclude("latitude"))
    .drop_nulls()
    .pivot(values="sza", index="month", on="tst", sort_columns=True)
)

(
    GT(sza_pivot, rowname_col="month")
    .data_color(
        domain=[90, 0],
        palette=["rebeccapurple", "white", "orange"],
        na_color="white",
    )
    .tab_header(
        title="Solar Zenith Angles from 05:30 to 12:00",
        subtitle=html("Average monthly values at latitude of 20&deg;N."),
    )
    .sub_missing(missing_text="")
)
""", """
sza_pivot <-
  sza |>
  filter(latitude == 20, tst <= "1200") |>
  select(-latitude) |>
  drop_na() |>
  pivot_wider(names_from = tst, values_from = sza, names_sort = TRUE)

sza_pivot |>
  gt(rowname_col = "month") |>
  data_color(
    domain = c(0, 90),
    palette = c("orange", "white", "#663399"),  # R has no rebeccapurple
    na_color = "white"
  ) |>
  tab_header(
    title = "Solar Zenith Angles from 05:30 to 12:00",
    subtitle = html("Average monthly values at latitude of 20&deg;N.")
  ) |>
  sub_missing(missing_text = "")
""":
  nbCode:
    let szaPivot = readCsv(newStringStream(szaCsv), inferSchemaLength = 0)  # every column as text
      .filter(col("latitude") == "20" and col("tst") <= lit("1200"))
      .drop("latitude")
      .dropNulls()
      .withColumns(col("sza").`cast`(Float64))
      .pivot(values = "sza", index = "month", on = "tst", sortColumns = true)

    let szaTbl = tabella(szaPivot, rownameCol = "month"):
      dataColor domain = (90.0, 0.0), palette = @["rebeccapurple", "white", "orange"],
        naColor = "white"
      tabHeader "Solar Zenith Angles from 05:30 to 12:00",
        html"Average monthly values at latitude of 20&deg;N."
      subMissing(missingText = "")
    nbTable szaTbl

tabelline """
gt's `data_color()` wants its domain from low to high, so the R tab turns the palette around
instead: 0° (the sun overhead) is orange, 90° (the sun on the horizon) purple, as in Python and
Nim, where the domain may run from high to low. R's colour names are not CSS's, and
`rebeccapurple` is CSS only: the R tab writes it as `#663399`.
"""

nbText: """
The Sports earnings example, the highest paid athletes of 2023, has [a page of its
own](sports_earnings.html).

The next example is the carbon intensity of electricity consumption, by Grant Chalmers
([source](https://gist.github.com/chalg/93ca29e202ab86e7d4caad44726372e4/d17c1b4ba608ae1c3df6ac7fc377065ae5708ba7),
[blog post with the R code](https://chalg.quarto.pub/carbon-intensity-of-electricity-consumption/)).
"""

tabs """
import warnings
from great_tables import GT, md, html, system_fonts
import pandas as pd

warnings.filterwarnings("ignore")
power_cie_prepared_tbl = pd.read_csv("../data/great-tables/examples/power_cie_prepared_tbl.csv")


# Create a Great Tables object
ciep_gt_tbl = GT(data=power_cie_prepared_tbl)

# Apply wider color ranges & formatting

gt_tbl = (
    ciep_gt_tbl.fmt_percent(
        columns=[
            "Hydro",
            "Nuclear",
            "Wind",
            "Solar",
            "Geothermal",
            "Biomass",
            "Gas",
            "Coal",
            "Oil",
            "Unknown",
            "Hydro Discharge",
            "Battery Discharge",
        ],
        decimals=1,
    )
    .fmt_number(columns=["CO2 Intensity"], decimals=0)
    .data_color(
        columns=["CO2 Intensity"],
        palette=[
            "#00A600",
            "#E6E600",
            "#E8C32E",
            "#D69C4E",
            "#Dc863B",
            "sienna",
            "sienna4",
            "tomato4",
            "brown",
        ],
        domain=[0, 900],
    )
    .data_color(
        columns=["Hydro", "Nuclear", "Wind", "Solar", "Geothermal"],
        palette=["#00A600", "chartreuse3", "chartreuse4", "snow"][::-1],
        domain=[0, 1],
    )
    .data_color(
        columns=["Hydro", "Geothermal"],
        palette=["#00A600", "chartreuse3", "chartreuse4", "snow"][::-1],
        domain=[0, 1],
    )
    .data_color(
        columns=["Biomass"], palette=["snow", "#EEC900", "#E8C32E", "#D69C4E"], domain=[0, 0.3]
    )
    .data_color(
        columns=["Gas", "Coal", "Oil"],
        palette=["tomato4", "sienna4", "#D69C4E", "#Dc863B", "snow"][::-1],
        domain=[0, 1],
    )
    .data_color(
        columns=["Zone", "Unknown", "Hydro Discharge", "Battery Discharge"],
        palette=["snow", "snow", "snow", "snow"],
    )
    .cols_width(
        {
            "CO2 Intensity": "58px",
            "Hydro": "58px",
            "Nuclear": "58px",
            "Wind": "58px",
            "Solar": "58px",
            "Geothermal": "58px",
            "Biomass": "58px",
            "Gas": "58px",
            "Coal": "58px",
            "Oil": "58px",
            "Unknown": "58px",
            "Hydro Discharge": "58px",
            "Battery Discharge": "58px",
        }
    )
    .tab_header(
        title=md(
            "2023 Mean **Carbon Intensity** (gCO2eq/kWh) and **Power Consumption** Breakdown (%)"
        )
    )
    .tab_source_note(
        md(
            '<br><div style="text-align: left;">'
            "**Source**: api.electricitymap.org"
            " | **Methodology**: https://www.electricitymaps.com/methodology."
            " Some emissions factors are based on IPCC 2014 defaults, while some are based on more accurate regional factors."
            " <br>All zones are publicly available on the *Carbon intensity and emission factors* tab via Google docs link<br>"
            "</div>"
            "<br>"
        )
    )
    .tab_options(
        source_notes_font_size="x-small",
        source_notes_padding=3,
        table_font_names=system_fonts("humanist"),
        data_row_padding="1px",
        heading_background_color="antiquewhite",
        source_notes_background_color="antiquewhite",
        column_labels_background_color="antiquewhite",
        table_background_color="snow",
        data_row_padding_horizontal=3,
        column_labels_padding_horizontal=58,
    )
    .cols_align(align="center")
    .cols_align(align="left", columns=["Zone"])
    .opt_table_outline()
)

gt_tbl
""", """
power_cie_prepared_tbl <- read.csv(
  "../data/great-tables/examples/power_cie_prepared_tbl.csv",
  check.names = FALSE
)

shares <- c(
  "Hydro", "Nuclear", "Wind", "Solar", "Geothermal", "Biomass", "Gas", "Coal",
  "Oil", "Unknown", "Hydro Discharge", "Battery Discharge"
)

power_cie_prepared_tbl |>
  gt() |>
  fmt_percent(columns = all_of(shares), decimals = 1) |>
  fmt_number(columns = "CO2 Intensity", decimals = 0) |>
  data_color(
    columns = "CO2 Intensity",
    palette = c(
      "#00A600", "#E6E600", "#E8C32E", "#D69C4E", "#Dc863B",
      "sienna", "sienna4", "tomato4", "brown"
    ),
    domain = c(0, 900)
  ) |>
  data_color(
    columns = c(Hydro, Nuclear, Wind, Solar, Geothermal),
    palette = rev(c("#00A600", "chartreuse3", "chartreuse4", "snow")),
    domain = c(0, 1)
  ) |>
  data_color(
    columns = Biomass,
    palette = c("snow", "#EEC900", "#E8C32E", "#D69C4E"),
    domain = c(0, 0.3)
  ) |>
  data_color(
    columns = c(Gas, Coal, Oil),
    palette = rev(c("tomato4", "sienna4", "#D69C4E", "#Dc863B", "snow")),
    domain = c(0, 1)
  ) |>
  data_color(
    columns = c(Zone, Unknown, `Hydro Discharge`, `Battery Discharge`),
    palette = c("snow", "snow", "snow", "snow")
  ) |>
  cols_width(-Zone ~ px(58)) |>
  tab_header(
    title = md("2023 Mean **Carbon Intensity** (gCO2eq/kWh) and **Power Consumption** Breakdown (%)")
  ) |>
  tab_source_note(
    md(paste0(
      '<br><div style="text-align: left;">',
      "**Source**: api.electricitymap.org",
      " | **Methodology**: https://www.electricitymaps.com/methodology.",
      " Some emissions factors are based on IPCC 2014 defaults, while some are based on more accurate regional factors.",
      " <br>All zones are publicly available on the *Carbon intensity and emission factors* tab via Google docs link<br>",
      "</div>",
      "<br>"
    ))
  ) |>
  opt_table_font(stack = "humanist") |>
  tab_options(
    source_notes.font.size = "x-small",
    source_notes.padding = px(3),
    data_row.padding = px(1),
    heading.background.color = "antiquewhite",
    source_notes.background.color = "antiquewhite",
    column_labels.background.color = "antiquewhite",
    table.background.color = "snow",
    data_row.padding.horizontal = px(3),
    column_labels.padding.horizontal = px(58)
  ) |>
  cols_align(align = "center") |>
  cols_align(align = "left", columns = Zone) |>
  opt_table_outline()
""":
  nbCode:
    let powerCie = readCsv(newStringStream(powerCieCsv), inferSchemaLength = 10_000)

    let widths = powerCie.columns[1 .. ^1].mapIt((it, "58px"))  # every column but Zone
    let shares = ["Hydro", "Nuclear", "Wind", "Solar", "Geothermal", "Biomass", "Gas", "Coal",
                  "Oil", "Unknown", "Hydro Discharge", "Battery Discharge"]

    let powerTbl = tabella(powerCie):
      fmtPercent shares, decimals = 1
      fmtNumber "CO2 Intensity", decimals = 0
      dataColor "CO2 Intensity", domain = (0.0, 900.0), palette = @["#00A600", "#E6E600",
        "#E8C32E", "#D69C4E", "#Dc863B", "sienna", "sienna4", "tomato4", "brown"]
      dataColor ["Hydro", "Nuclear", "Wind", "Solar", "Geothermal"], domain = (0.0, 1.0),
        palette = @["snow", "chartreuse4", "chartreuse3", "#00A600"]
      dataColor "Biomass", domain = (0.0, 0.3), palette = @["snow", "#EEC900", "#E8C32E", "#D69C4E"]
      dataColor ["Gas", "Coal", "Oil"], domain = (0.0, 1.0),
        palette = @["snow", "#Dc863B", "#D69C4E", "sienna4", "tomato4"]
      dataColor ["Zone", "Unknown", "Hydro Discharge", "Battery Discharge"],
        palette = @["snow", "snow", "snow", "snow"]
      colsWidth widths
      tabHeader md"2023 Mean **Carbon Intensity** (gCO2eq/kWh) and **Power Consumption** Breakdown (%)"
      tabSourceNote md("**Source**: api.electricitymap.org" &
        " | **Methodology**: https://www.electricitymaps.com/methodology." &
        " Some emissions factors are based on IPCC 2014 defaults, while some are based on more accurate regional factors." &
        "<br>All zones are publicly available on the *Carbon intensity and emission factors* tab via Google docs link")
      optTableFont systemFonts("humanist")
      tabOptions(sourceNotesFontSize = "x-small", sourceNotesPadding = "3px",
                 dataRowPadding = "1px", headingBackgroundColor = "antiquewhite",
                 sourceNotesBackgroundColor = "antiquewhite",
                 columnLabelsBackgroundColor = "antiquewhite", tableBackgroundColor = "snow",
                 dataRowPaddingHorizontal = "3px", columnLabelsPaddingHorizontal = "58px")
      colsAlign alCenter
      colsAlign alLeft, "Zone"
      optTableOutline()
    nbTable powerTbl

tabelline """
CSS names 148 colours, R 657: tabelline knows them all, as gt and Great Tables do, so R's
numbered shades (`sienna4`, `chartreuse3`) are written as they are; in a table they become
hex values, which CSS reads. The source note is Markdown with its line breaks
and left alignment left out: the notes of a tabelline table are already aligned to the left.
"""

nbText: """
The last example is a year of sales of coffee equipment, by Michael Chow
([source](https://github.com/machow/coffee-sales-data/),
[notebook](https://github.com/machow/coffee-sales-data/blob/main/example_notebook.ipynb)).
"""

tabs """
import polars as pl
import polars.selectors as cs
from great_tables import GT, loc, style

coffee_sales = pl.read_ndjson("../data/great-tables/examples/coffee-sales.ndjson")

sel_rev = cs.starts_with("revenue")
sel_prof = cs.starts_with("profit")

# yo

coffee_table = (
    GT(coffee_sales)
    .tab_header("Sales of Coffee Equipment")
    .tab_spanner(label="Revenue", columns=sel_rev)
    .tab_spanner(label="Profit", columns=sel_prof)
    .cols_label(
        revenue_dollars="Amount",
        profit_dollars="Amount",
        revenue_pct="Percent",
        profit_pct="Percent",
        monthly_sales="Monthly Sales",
        icon="",
        product="Product",
    )
    # formatting ----
    .fmt_number(
        columns=cs.ends_with("dollars"),
        compact=True,
        pattern="${x}",
        n_sigfig=3,
    )
    .fmt_percent(columns=cs.ends_with("pct"), decimals=0)
    # style ----
    .tab_style(
        style=style.fill(color="aliceblue"),
        locations=loc.body(columns=sel_rev),
    )
    .tab_style(
        style=style.fill(color="papayawhip"),
        locations=loc.body(columns=sel_prof),
    )
    .tab_style(
        style=style.text(weight="bold"),
        locations=loc.body(rows=pl.col("product") == "Total"),
    )
    .fmt_nanoplot("monthly_sales", plot_type="bar")
    .fmt_image("icon", path="../data/great-tables/examples/coffee-table-icons/")
    .sub_missing(missing_text="")
)

coffee_table
""", """
coffee_sales <-
  jsonlite::stream_in(
    file("../data/great-tables/examples/coffee-sales.ndjson"),
    verbose = FALSE
  ) |>
  as_tibble() |>
  unnest_wider(monthly_sales, names_sep = "_")

coffee_sales |>
  gt() |>
  tab_header("Sales of Coffee Equipment") |>
  tab_spanner(label = "Revenue", columns = starts_with("revenue")) |>
  tab_spanner(label = "Profit", columns = starts_with("profit")) |>
  cols_label(
    revenue_dollars = "Amount",
    profit_dollars = "Amount",
    revenue_pct = "Percent",
    profit_pct = "Percent",
    icon = "",
    product = "Product"
  ) |>
  # formatting ----
  fmt_number(
    columns = ends_with("dollars"),
    suffixing = TRUE,
    pattern = "${x}",
    n_sigfig = 3
  ) |>
  fmt_percent(columns = ends_with("pct"), decimals = 0) |>
  # style ----
  tab_style(
    style = cell_fill(color = "aliceblue"),
    locations = cells_body(columns = starts_with("revenue"))
  ) |>
  tab_style(
    style = cell_fill(color = "papayawhip"),
    locations = cells_body(columns = starts_with("profit"))
  ) |>
  tab_style(
    style = cell_text(weight = "bold"),
    locations = cells_body(rows = product == "Total")
  ) |>
  cols_nanoplot(
    columns = starts_with("monthly_sales_"),
    plot_type = "bar",
    new_col_name = "monthly_sales",
    new_col_label = "Monthly Sales"
  ) |>
  fmt_image(columns = icon, path = "../data/great-tables/examples/coffee-table-icons/") |>
  sub_missing(missing_text = "")
""":
  nbCode:
    let coffeeSales = readNdjson(newStringStream(coffeeSalesNdjson))

    let selRev = startsWith("revenue")
    let selProf = startsWith("profit")

    let coffeeTable = tabella(coffeeSales):
      tabHeader "Sales of Coffee Equipment"
      tabSpanner "Revenue", selRev
      tabSpanner "Profit", selProf
      colsLabel:
        revenue_dollars: "Amount"
        profit_dollars: "Amount"
        revenue_pct: "Percent"
        profit_pct: "Percent"
        monthly_sales: "Monthly Sales"
        icon: ""
        product: "Product"
      # formatting ----
      fmtNumber endsWith("dollars"), compact = true, pattern = "${x}", nSigfig = 3
      fmtPercent endsWith("pct"), decimals = 0
      # style ----
      tabStyle style.fill("aliceblue"), loc.body(cols = selRev)
      tabStyle style.fill("papayawhip"), loc.body(cols = selProf)
      tabStyle style.text(weight = "bold"), loc.body(rows = where(it["product"] == "Total"))
      fmtNanoplot "monthly_sales", plotType = "bar"
      fmtImage "icon", path = coffeeIcons
      subMissing(missingText = "")
    nbTable coffeeTable

tabelline """
`nSigfig = 3` keeps three significant figures, as Great Tables' `n_sigfig`: $904K and $2.05M.
The monthly sales are a list in each row, and a list column of a nanuq data frame becomes a
list in tabelline, which the nanoplot draws. gt's nanoplots take their values from
columns, so the R tab spreads the twelve months over twelve columns first.
"""

bookSave()
Made with tabelline, nimib and nimibook. The Nim code ran when this page was built; the Python ran with Great Tables 1.1.0 and the R with gt 1.4.0.