Write ggsql queries — a grammar of graphics for SQL. Use when the user wants to create, modify, or understand a ggsql visualization query.
VISUALISE (or VISUALIZE). Everything after this is the visualization query.FROM clause.SELECT name, score_a, score_b FROM 'dataset.csv' WHERE value > 50
VISUALISE score_a AS x, score_b AS y
[DRAW / PLACE / SCALE / FACET / PROJECT / LABEL clauses]
FROM. Use when referencing a table, file, CTE, or built-in dataset directly without a trailing SELECT.VISUALISE score_a AS x, score_b AS y FROM 'dataset.csv'
DRAW point
WITH summary AS (SELECT category, COUNT(*) AS n FROM 'dataset.csv' GROUP BY category)
VISUALISE category AS x, n AS y FROM summary
DRAW bar
VISUALISE ... FROM or DRAW ... MAPPING ... FROM:FROM sales, FROM my_cteFROM 'data.parquet', FROM 'data.csv'FROM ggsql:penguins, FROM ggsql:airqualityVISUALISE <mapping>, ... FROM <data-source>
column AS aesthetic — e.g. revenue AS ycolumn — column name must match aesthetic name, e.g. x maps to x* — all columns with names matching aesthetics are mapped'red' AS fill, 42 AS size — literal values mapped to aestheticVISUALISE bill_len AS x, bill_dep AS y, species AS fill FROM ggsql:penguins
VISUALISE * FROM my_table
VISUALISE FROM ggsql:penguins
DRAW <layer-type>
MAPPING <mapping>, ... FROM <data-source>
REMAPPING <stat-property> AS <aesthetic>, ...
SETTING <param> => <value>, ...
FILTER <condition>
PARTITION BY <column>, ...
ORDER BY <column>, ...
FROM for layer-specific data.null to prevent inheriting a global mapping: MAPPING null AS colorDRAW histogram
MAPPING body_mass AS x
REMAPPING density AS y -- use density instead of default count
DRAW point
SETTING size => 5, opacity => 0.7, stroke => 'red'
SETTING position => 'identity' -- no adjustment (default for most)
SETTING position => 'stack' -- stack (default for bar, histogram, area)
SETTING position => 'dodge' -- side by side (default for boxplot, violin)
SETTING position => 'jitter' -- random offset
DRAW point
FILTER sex = 'female' AND body_mass > 4000
DRAW line
MAPPING Day AS x, Temp AS y
PARTITION BY Month
DRAW path
ORDER BY timestamp
PLACE <layer-type>
SETTING <aesthetic/param> => <value>, ...
PLACE point SETTING x => 5, y => 10, color => 'red'
PLACE rule SETTING y => 70, linetype => 'dotted'
PLACE text SETTING x => (34, 44), y => (66, 49), label => ('Mean = 34', 'Mean = 44')
SCALE <type> <aesthetic> FROM <input-range> TO <output-range> VIA <transform>
SETTING <param> => <value>, ...
RENAMING <value> => <label>, ...
aesthetic are optional.CONTINUOUS — continuous numeric/temporal dataDISCRETE — categorical/string dataBINNED — bin continuous data into discrete groups (never auto-selected, must be explicit)ORDINAL — ordered discrete data (never auto-selected, must be explicit)IDENTITY — pass data through unchanged (no legend created)x, y, fill, stroke, color (sets both fill and stroke), opacity, size, linewidth, linetype, shape, panel (facet), row, column.SCALE x ...FROM (min, max) — use null to infer from data: FROM (0, null)FROM ('A', 'B', 'C') — controls order, omitted values are nulledFROM ('Torgersen', 'Biscoe', null)TO ('red', 'blue', 'green'), TO (1, 6)TO viridis, TO dark2, TO tableau10linear, log, log2, ln, exp10, exp2, exp, sqrt, square, asinh, pseudo_log, pseudo_log2, pseudo_ln, integerdate, datetime, time — automatically chosen for date/datetime/time columns.string, boolSCALE x VIA date -- treat x as temporal
SCALE y VIA log -- log transform
SCALE size VIA square -- scale by radius not area
expand — expansion factor, scalar or (mult, add). Default 0.05. Only for x/y.oob — out-of-bounds: 'keep' (default for x/y), 'censor' (default for others), 'squish'breaks — integer count, array of values, or interval string for temporal (e.g. '2 months', 'week')pretty — boolean, default true. Use Wilkinson's algorithm for nice breaks.reverse — boolean, default false. Reverse scale direction.closed — 'left' (default) or 'right'reverse — booleanSCALE x SETTING breaks => '2 months'
SCALE y FROM (0, 100) SETTING oob => 'squish'
SCALE BINNED x SETTING breaks => 10, pretty => false
RENAMING 'Adelie' => 'Pygoscelis adeliae', 'adelie' => null -- direct / suppress
RENAMING * => '{} mm' -- string interpolation
RENAMING * => '{:Title}' -- formatters: Title, UPPER, lower, time %B %Y, num %.1f
FACET <column> BY <column>
SETTING <param> => <value>, ...
FACET region — wrap layout, aesthetic name is panelFACET region BY category — grid layout, aesthetics are row and columnfree — null (default/fixed), 'x', 'y', or ('x', 'y') for independent scalesmissing — 'repeat' (default, show layer in all panels) or 'null' (only show in null panel)ncol/nrow — layout dimensions for 1D faceting (only one allowed)FACET region
SCALE panel
RENAMING 'N' => 'North', 'S' => 'South'
FACET island
SCALE panel FROM ('Biscoe', 'Dream')
PROJECT <aesthetic>, ... TO <coord-type>
SETTING <param> => <value>, ...
clip (boolean, default true), ratio (aspect ratio number or null)x, yclip, start (degrees, default 0 = 12 o'clock), end (degrees, default start+360), inner (0-1 proportion for donut hole, default 0)radius (primary), angle (secondary)PROJECT y, x TO cartesian. If no PROJECT clause, coordinate type is inferred from mappings (x/y = cartesian, radius/angle = polar).PROJECT TO polar SETTING inner => 0.5 -- donut chart
PROJECT TO polar SETTING start => -90, end => 90 -- half-circle gauge
LABEL
<aesthetic/title> => <string>, ...
title — main titlesubtitle — subtitle below titlecaption — text below the plotx, y, fill, color, etc.null to suppress a label: fill => nullLABEL
title => 'Sales by Region',
subtitle => 'Q4 2024 data',
x => 'Date',
y => 'Revenue (USD)',
fill => 'Region',
caption => 'Source: internal sales database'
position, orientation ('aligned'/'transposed').count, proportion. Properties: weight. Settings: position (default 'stack'), width (0-1). Orientation inferred from mapping (categories on x = vertical, on y = horizontal).DRAW bar MAPPING species AS x -- auto-count
DRAW bar MAPPING species AS x, total AS y -- pre-computed
DRAW bar MAPPING species AS x, sex AS fill -- stacked (default)
SETTING position => 'dodge' -- side by side
count, density. Default remapping: count AS <secondary>. Settings: position (default 'stack'), bins (default 30), binwidth, closed ('left'/'right').DRAW histogram MAPPING body_mass AS x SETTING binwidth => 100
DRAW histogram MAPPING body_mass AS x REMAPPING density AS y -- density instead of count
density, intensity. Settings: position (default 'identity'), bandwidth, adjust (default 1), kernel ('gaussian' default, 'epanechnikov', 'triangular', 'rectangular', 'biweight', 'cosine').type, value. Settings: position (default 'dodge'), outliers (default true), coef (whisker IQR multiple, default 1.5), width (default 0.9).density, intensity. Default remapping: density AS offset. Settings: position (default 'dodge'), bandwidth, adjust, kernel (same as density), width (default 0.9), side ('both'/'left'/'bottom'/'right'/'top'), tails (number or null, default 3).intensity. Settings: method ('nw' default, 'ols', 'tls'), bandwidth, adjust, kernel (same as density, nw only).position (default 'stack'), orientation, total (normalize stacks), center (boolean, for steamgraph).range instead.slope (for diagonal: y = a + slope * x).offset (number or (h, v)), format (string interpolation like RENAMING). hjust: 'left'/'right'/'centre' or 0-1. vjust: 'top'/'bottom'/'middle' or 0-1.width (hinge width in points, default 10, null to hide).position setting where applicable.ggsql10 (default), tableau10, category10, set1, set2, set3, dark2, paired, pastel1, pastel2, accent, kelly22sequential (default), viridis, plasma, magma, inferno, cividis, blues, greens, oranges, reds, purples, greys, ylgnbu, ylorbr, ylorrd, batlow, hawaii, lajolla, turku, and morevik/diverging, rdbu, rdylbu, rdylgn, spectral, brbg, prgn, piyg, puor, berlin, roma, and moreromao/cyclic, bamo, broco, corko, viko-- Pie chart
VISUALISE species AS fill FROM ggsql:penguins
DRAW bar
PROJECT TO polar
-- Horizontal bar chart
DRAW bar MAPPING species AS y
-- Multi-series line chart
VISUALISE Date AS x
DRAW line MAPPING Temp AS y, 'Temperature' AS color
DRAW line MAPPING Ozone AS y, 'Ozone' AS color
SCALE x VIA date
-- Lollipop chart
SELECT ROUND(bill_dep) AS bill_dep, COUNT(*) AS n FROM ggsql:penguins GROUP BY 1
VISUALISE bill_dep AS x
DRAW range MAPPING 0 AS ymin, n AS ymax SETTING width => null
DRAW point MAPPING n AS y
-- Ridgeline / joy plot
VISUALISE Temp AS x, Month AS y FROM ggsql:airquality
DRAW violin SETTING width => 4, side => 'top'
SCALE ORDINAL y
-- Bar labels
SELECT island, COUNT(*) AS n FROM ggsql:penguins GROUP BY island
VISUALISE island AS x, n AS y
DRAW bar
DRAW text MAPPING n AS label SETTING vjust => 'top', offset => (0, -11), fill => 'white'
-- CTEs with separate layer data
WITH temps AS (SELECT Date, Temp as value FROM ggsql:airquality),
ozone AS (SELECT Date, Ozone as value FROM ggsql:airquality WHERE Ozone IS NOT NULL)
VISUALISE
DRAW line MAPPING Date AS x, value AS y, 'Temperature' AS color FROM temps
DRAW point MAPPING Date AS x, value AS y, 'Ozone' AS color FROM ozone
SCALE x VIA date
ggsql CLI should be on the PATH. Subcommands: exec <QUERY>, run <FILE>, validate <QUERY>, parse <QUERY>. Common options: --reader <URI> (default duckdb://memory), --writer <FORMAT> (default vegalite), --output <PATH>, -v (verbose).ggsql validate "VISUALISE x, y FROM data DRAW point"
ggsql exec "VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point" -v
ggsql run query.sql --output chart.vl.json
ggsql:penguins or ggsql:airquality as example data when no specific data is mentioned.ggsql validate "<query>". When the user wants to see the output, use ggsql exec "<query>" -v.