{"id":"ggsql","name":"ggsql","summary":"ggsqlクエリを書いてください — SQLのグラフィックの文法です。ユーザーがggsqlの可視化クエリを作成、修正、または理解したい場合に使います。","body":"# ggsql Query Writer\n\nggsql is a SQL extension for declarative data visualization based on Grammar of Graphics principles. It lets users combine SQL data queries with visualization specifications in a single, composable syntax.\n\nWhen the user describes a visualization they want, write a valid ggsql query. Use ONLY syntax documented below. NEVER invent clauses, settings, aesthetics, or layer types.\n\n## Query structure\n\nA ggsql query has two parts:\n\n1. **SQL part** (optional): Standard SQL executed on the backend. Any tables, CTEs, or SELECT results are available to the visualization.\n2. **VISUALISE part** (required): Begins with `VISUALISE` (or `VISUALIZE`). Everything after this is the visualization query.\n\nThere are two patterns for combining SQL with VISUALISE:\n\n### Pattern A: SELECT → VISUALISE\n\nThe last SQL statement is a SELECT. Data flows from its result set into VISUALISE, which has no `FROM` clause.\n\n```ggsql\nSELECT name, score_a, score_b FROM 'dataset.csv' WHERE value > 50\nVISUALISE score_a AS x, score_b AS y\n[DRAW / PLACE / SCALE / FACET / PROJECT / LABEL clauses]\n```\n\nWorks with any SQL that ends in a SELECT: bare SELECT, WITH...SELECT, UNION/INTERSECT/EXCEPT.\n\n### Pattern B: VISUALISE FROM\n\nVISUALISE provides its own data source via `FROM`. Use when referencing a table, file, CTE, or built-in dataset directly without a trailing SELECT.\n\n```ggsql\nVISUALISE score_a AS x, score_b AS y FROM 'dataset.csv'\nDRAW point\n```\n\n```ggsql\nWITH summary AS (SELECT category, COUNT(*) AS n FROM 'dataset.csv' GROUP BY category)\nVISUALISE category AS x, n AS y FROM summary\nDRAW bar\n```\n\n## Data sources\n\nData sources can appear in `VISUALISE ... FROM` or `DRAW ... MAPPING ... FROM`:\n\n- **Table/CTE name** (unquoted): `FROM sales`, `FROM my_cte`\n- **File path** (single-quoted string): `FROM 'data.parquet'`, `FROM 'data.csv'`\n- **Built-in datasets**: `FROM ggsql:penguins`, `FROM ggsql:airquality`\n\n## VISUALISE clause\n\nMarks the start of the visualization. Optionally defines global mappings inherited by all layers.\n\n```\nVISUALISE <mapping>, ... FROM <data-source>\n```\n\n### Mapping forms\n\n- **Explicit**: `column AS aesthetic` — e.g. `revenue AS y`\n- **Implicit**: `column` — column name must match aesthetic name, e.g. `x` maps to `x`\n- **Wildcard**: `*` — all columns with names matching aesthetics are mapped\n- **Constants**: `'red' AS fill`, `42 AS size` — literal values mapped to aesthetic\n\n```ggsql\nVISUALISE bill_len AS x, bill_dep AS y, species AS fill FROM ggsql:penguins\nVISUALISE * FROM my_table\nVISUALISE FROM ggsql:penguins\n```\n\n## DRAW clause\n\nDefines a layer. Multiple DRAW clauses stack layers (first = bottom, last = top).\n\n```\nDRAW <layer-type>\n  MAPPING <mapping>, ... FROM <data-source>\n  REMAPPING <stat-property> AS <aesthetic>, ...\n  SETTING <param> => <value>, ...\n  FILTER <condition>\n  PARTITION BY <column>, ...\n  ORDER BY <column>, ...\n```\n\nAll subclauses are optional if VISUALISE provides global mappings and data.\n\n### MAPPING\n\nSame syntax as VISUALISE mappings. Layer mappings merge with global mappings (layer takes precedence). Can include `FROM` for layer-specific data.\n\n- Use `null` to prevent inheriting a global mapping: `MAPPING null AS color`\n\n### REMAPPING\n\nFor statistical layers (histogram, density, boxplot, violin, smooth, bar without y). Maps calculated statistics to aesthetics. Each layer documents its available stats and default remapping.\n\n```ggsql\nDRAW histogram\n  MAPPING body_mass AS x\n  REMAPPING density AS y  -- use density instead of default count\n```\n\n### SETTING\n\nSet literal aesthetic values or layer parameters. Aesthetics set here bypass scales.\n\n```ggsql\nDRAW point\n  SETTING size => 5, opacity => 0.7, stroke => 'red'\n```\n\n**Position adjustment** is a special setting:\n```ggsql\nSETTING position => 'identity'   -- no adjustment (default for most)\nSETTING position => 'stack'      -- stack (default for bar, histogram, area)\nSETTING position => 'dodge'      -- side by side (default for boxplot, violin)\nSETTING position => 'jitter'     -- random offset\n```\n\n### FILTER\n\nSQL WHERE condition applied to layer data. Content is passed to the database:\n```ggsql\nDRAW point\n  FILTER sex = 'female' AND body_mass > 4000\n```\n\n### PARTITION BY\n\nAdditional grouping columns beyond mapped discrete aesthetics:\n```ggsql\nDRAW line\n  MAPPING Day AS x, Temp AS y\n  PARTITION BY Month\n```\n\n### ORDER BY\n\nControls record order (important for path layers):\n```ggsql\nDRAW path\n  ORDER BY timestamp\n```\n\n## PLACE clause\n\nCreates annotation layers with literal values only (no data mappings). Supports tuples for multiple annotations.\n\n```\nPLACE <layer-type>\n  SETTING <aesthetic/param> => <value>, ...\n```\n\n```ggsql\nPLACE point SETTING x => 5, y => 10, color => 'red'\nPLACE rule SETTING y => 70, linetype => 'dotted'\nPLACE text SETTING x => (34, 44), y => (66, 49), label => ('Mean = 34', 'Mean = 44')\n```\n\n## SCALE clause\n\nControls how data values are translated to aesthetic values. Sensible defaults are always provided.\n\n```\nSCALE <type> <aesthetic> FROM <input-range> TO <output-range> VIA <transform>\n  SETTING <param> => <value>, ...\n  RENAMING <value> => <label>, ...\n```\n\nAll parts except `aesthetic` are optional.\n\n### Scale types (optional, placed before aesthetic)\n\n- `CONTINUOUS` — continuous numeric/temporal data\n- `DISCRETE` — categorical/string data\n- `BINNED` — bin continuous data into discrete groups (never auto-selected, must be explicit)\n- `ORDINAL` — ordered discrete data (never auto-selected, must be explicit)\n- `IDENTITY` — pass data through unchanged (no legend created)\n\nIf omitted, type is inferred from data.\n\n### Aesthetic names\n\nUse the base name: `x`, `y`, `fill`, `stroke`, `color` (sets both fill and stroke), `opacity`, `size`, `linewidth`, `linetype`, `shape`, `panel` (facet), `row`, `column`.\n\nFor position families (xmin/xmax/xend/ymin/ymax/yend), scale with the base name: `SCALE x ...`\n\n### FROM (input range)\n\n- Continuous: `FROM (min, max)` — use `null` to infer from data: `FROM (0, null)`\n- Discrete: `FROM ('A', 'B', 'C')` — controls order, omitted values are nulled\n- Include null explicitly: `FROM ('Torgersen', 'Biscoe', null)`\n\n### TO (output range)\n\n- Array of values: `TO ('red', 'blue', 'green')`, `TO (1, 6)`\n- Named palette: `TO viridis`, `TO dark2`, `TO tableau10`\n\n### VIA (transform)\n\nContinuous transforms: `linear`, `log`, `log2`, `ln`, `exp10`, `exp2`, `exp`, `sqrt`, `square`, `asinh`, `pseudo_log`, `pseudo_log2`, `pseudo_ln`, `integer`\n\nTemporal transforms: `date`, `datetime`, `time` — automatically chosen for date/datetime/time columns.\n\nDiscrete transforms: `string`, `bool`\n\n```ggsql\nSCALE x VIA date        -- treat x as temporal\nSCALE y VIA log         -- log transform\nSCALE size VIA square   -- scale by radius not area\n```\n\n### SETTING\n\nContinuous/binned scales:\n- `expand` — expansion factor, scalar or `(mult, add)`. Default `0.05`. Only for x/y.\n- `oob` — out-of-bounds: `'keep'` (default for x/y), `'censor'` (default for others), `'squish'`\n- `breaks` — integer count, array of values, or interval string for temporal (e.g. `'2 months'`, `'week'`)\n- `pretty` — boolean, default `true`. Use Wilkinson's algorithm for nice breaks.\n- `reverse` — boolean, default `false`. Reverse scale direction.\n\nBinned scales additionally:\n- `closed` — `'left'` (default) or `'right'`\n\nDiscrete/ordinal scales:\n- `reverse` — boolean\n\n```ggsql\nSCALE x SETTING breaks => '2 months'\nSCALE y FROM (0, 100) SETTING oob => 'squish'\nSCALE BINNED x SETTING breaks => 10, pretty => false\n```\n\n### RENAMING\n\nRename break labels. Direct renaming, wildcard formatting, or both (direct takes priority):\n\n```ggsql\nRENAMING 'Adelie' => 'Pygoscelis adeliae', 'adelie' => null  -- direct / suppress\nRENAMING * => '{} mm'                -- string interpolation\nRENAMING * => '{:Title}'             -- formatters: Title, UPPER, lower, time %B %Y, num %.1f\n```\n\n## FACET clause\n\nSplit data into small multiples.\n\n```\nFACET <column> BY <column>\n  SETTING <param> => <value>, ...\n```\n\n- 1D: `FACET region` — wrap layout, aesthetic name is `panel`\n- 2D: `FACET region BY category` — grid layout, aesthetics are `row` and `column`\n\n### Settings\n\n- `free` — `null` (default/fixed), `'x'`, `'y'`, or `('x', 'y')` for independent scales\n- `missing` — `'repeat'` (default, show layer in all panels) or `'null'` (only show in null panel)\n- `ncol`/`nrow` — layout dimensions for 1D faceting (only one allowed)\n\n### Customizing strip labels\n\nUse SCALE on the facet aesthetic:\n```ggsql\nFACET region\nSCALE panel\n  RENAMING 'N' => 'North', 'S' => 'South'\n```\n\n### Filtering panels\n\nUse SCALE FROM to select which panels to show:\n```ggsql\nFACET island\nSCALE panel FROM ('Biscoe', 'Dream')\n```\n\n## PROJECT clause\n\nControls the coordinate system.\n\n```\nPROJECT <aesthetic>, ... TO <coord-type>\n  SETTING <param> => <value>, ...\n```\n\n### Coordinate types\n\n**cartesian** (default) — horizontal x, vertical y\n- Settings: `clip` (boolean, default true), `ratio` (aspect ratio number or null)\n- Default aesthetics: `x`, `y`\n\n**polar** — angle + radius from center\n- Settings: `clip`, `start` (degrees, default 0 = 12 o'clock), `end` (degrees, default start+360), `inner` (0-1 proportion for donut hole, default 0)\n- Default aesthetics: `radius` (primary), `angle` (secondary)\n\nSwap aesthetic order to flip axes: `PROJECT y, x TO cartesian`. If no PROJECT clause, coordinate type is inferred from mappings (x/y = cartesian, radius/angle = polar).\n\n```ggsql\nPROJECT TO polar SETTING inner => 0.5  -- donut chart\nPROJECT TO polar SETTING start => -90, end => 90  -- half-circle gauge\n```\n\n## LABEL clause\n\nOverride default axis/legend labels and add titles.\n\n```\nLABEL\n  <aesthetic/title> => <string>, ...\n```\n\nAvailable labels:\n- `title` — main title\n- `subtitle` — subtitle below title\n- `caption` — text below the plot\n- Any aesthetic name — axis/legend title: `x`, `y`, `fill`, `color`, etc.\n- Use `null` to suppress a label: `fill => null`\n\n```ggsql\nLABEL\n  title => 'Sales by Region',\n  subtitle => 'Q4 2024 data',\n  x => 'Date',\n  y => 'Revenue (USD)',\n  fill => 'Region',\n  caption => 'Source: internal sales database'\n```\n\n---\n\n## Layer types\n\n### point\nScatterplot. Required: x, y. Optional: size, colour, stroke, fill, opacity, shape.\n\n### line\nLine plot sorted along primary axis. Required: x, y. Optional: colour/stroke, opacity, linewidth, linetype. Settings: `position`, `orientation` (`'aligned'`/`'transposed'`).\n\n### path\nLike line but connects points in data order (not sorted). Same aesthetics as line.\n\n### bar\nBar chart. Auto-counts if y not provided. Optional: x (categories), y (height), fill, colour, stroke. Stats: `count`, `proportion`. Properties: `weight`. Settings: `position` (default `'stack'`), `width` (0-1). Orientation inferred from mapping (categories on x = vertical, on y = horizontal).\n\n```ggsql\nDRAW bar MAPPING species AS x                              -- auto-count\nDRAW bar MAPPING species AS x, total AS y                  -- pre-computed\nDRAW bar MAPPING species AS x, sex AS fill                 -- stacked (default)\n  SETTING position => 'dodge'                              -- side by side\n```\n\n### histogram\nBins continuous data. Required: x. Stats: `count`, `density`. Default remapping: `count AS <secondary>`. Settings: `position` (default `'stack'`), `bins` (default 30), `binwidth`, `closed` (`'left'`/`'right'`).\n\n```ggsql\nDRAW histogram MAPPING body_mass AS x SETTING binwidth => 100\nDRAW histogram MAPPING body_mass AS x REMAPPING density AS y  -- density instead of count\n```\n\n### density\nKernel density estimation. Required: x. Stats: `density`, `intensity`. Settings: `position` (default `'identity'`), `bandwidth`, `adjust` (default 1), `kernel` (`'gaussian'` default, `'epanechnikov'`, `'triangular'`, `'rectangular'`, `'biweight'`, `'cosine'`).\n\n### boxplot\nFive-number summary with outliers. Required: x (categorical), y (continuous). Stats: `type`, `value`. Settings: `position` (default `'dodge'`), `outliers` (default true), `coef` (whisker IQR multiple, default 1.5), `width` (default 0.9).\n\n### violin\nMirrored kernel density for groups. Required: x (categorical), y (continuous). Stats: `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).\n\n### smooth\nTrendline. Required: x, y. Stats: `intensity`. Settings: `method` (`'nw'` default, `'ols'`, `'tls'`), `bandwidth`, `adjust`, `kernel` (same as density, nw only).\n\n### area\nArea chart anchored at zero. Required: x, y. Settings: `position` (default `'stack'`), `orientation`, `total` (normalize stacks), `center` (boolean, for steamgraph).\n\n### ribbon\nLike area but with explicit ymin/ymax (unanchored). Required: x, ymin, ymax.\n\n### segment\nLine segments between two endpoints. Required: x, y, xend, yend. For axis-aligned intervals where one coordinate is shared between start and end, use `range` instead.\n\n### rule\nReference lines spanning the full panel. Required: x or y. Optional: `slope` (for diagonal: `y = a + slope * x`).\n\n### text\nText labels. Required: x, y, label. Settings: `offset` (number or `(h, v)`), `format` (string interpolation like RENAMING). `hjust`: `'left'`/`'right'`/`'centre'` or 0-1. `vjust`: `'top'`/`'bottom'`/`'middle'` or 0-1.\n\n### rect\nRectangles. Required: pick 2 per axis from center (x/y), min (xmin/ymin), max (xmax/ymax), width, height. Or just center (defaults width/height to 1).\n\n### polygon\nClosed shapes from ordered coordinates. Required: x, y. Use PARTITION BY to separate distinct polygons.\n\n### range\nRange/interval display between two values along the secondary axis. Required: x, ymin, ymax. Settings: `width` (hinge width in points, default 10, null to hide).\n\nAll layers accept common optional aesthetics (colour/stroke, fill, opacity, linewidth, linetype) and `position` setting where applicable.\n\n---\n\n## Named color palettes\n\n- **Discrete**: `ggsql10` (default), `tableau10`, `category10`, `set1`, `set2`, `set3`, `dark2`, `paired`, `pastel1`, `pastel2`, `accent`, `kelly22`\n- **Sequential**: `sequential` (default), `viridis`, `plasma`, `magma`, `inferno`, `cividis`, `blues`, `greens`, `oranges`, `reds`, `purples`, `greys`, `ylgnbu`, `ylorbr`, `ylorrd`, `batlow`, `hawaii`, `lajolla`, `turku`, and more\n- **Diverging**: `vik`/`diverging`, `rdbu`, `rdylbu`, `rdylgn`, `spectral`, `brbg`, `prgn`, `piyg`, `puor`, `berlin`, `roma`, and more\n- **Cyclic**: `romao`/`cyclic`, `bamo`, `broco`, `corko`, `viko`\n\n---\n\n## Common patterns\n\n```ggsql\n-- Pie chart\nVISUALISE species AS fill FROM ggsql:penguins\nDRAW bar\nPROJECT TO polar\n\n-- Horizontal bar chart\nDRAW bar MAPPING species AS y\n\n-- Multi-series line chart\nVISUALISE Date AS x\nDRAW line MAPPING Temp AS y, 'Temperature' AS color\nDRAW line MAPPING Ozone AS y, 'Ozone' AS color\nSCALE x VIA date\n\n-- Lollipop chart\nSELECT ROUND(bill_dep) AS bill_dep, COUNT(*) AS n FROM ggsql:penguins GROUP BY 1\nVISUALISE bill_dep AS x\nDRAW range MAPPING 0 AS ymin, n AS ymax SETTING width => null\nDRAW point MAPPING n AS y\n\n-- Ridgeline / joy plot\nVISUALISE Temp AS x, Month AS y FROM ggsql:airquality\nDRAW violin SETTING width => 4, side => 'top'\nSCALE ORDINAL y\n\n-- Bar labels\nSELECT island, COUNT(*) AS n FROM ggsql:penguins GROUP BY island\nVISUALISE island AS x, n AS y\nDRAW bar\nDRAW text MAPPING n AS label SETTING vjust => 'top', offset => (0, -11), fill => 'white'\n\n-- CTEs with separate layer data\nWITH temps AS (SELECT Date, Temp as value FROM ggsql:airquality),\nozone AS (SELECT Date, Ozone as value FROM ggsql:airquality WHERE Ozone IS NOT NULL)\nVISUALISE\nDRAW line MAPPING Date AS x, value AS y, 'Temperature' AS color FROM temps\nDRAW point MAPPING Date AS x, value AS y, 'Ozone' AS color FROM ozone\nSCALE x VIA date\n```\n\n---\n\n## CLI\n\nThe `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).\n\n```bash\nggsql validate \"VISUALISE x, y FROM data DRAW point\"\nggsql exec \"VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point\" -v\nggsql run query.sql --output chart.vl.json\n```\n\n---\n\n## Additional References\n\n* https://ggsql.org/syntax/index.llms.md — Online documentation with the latest syntax\n\n---\n\n## Instructions for responding\n\n1. Write a complete, valid ggsql query matching the user's request.\n2. Use SQL CTEs/queries before VISUALISE when data shaping is needed.\n3. Choose the simplest layer types and settings that achieve the goal.\n4. Include SCALE clauses when the defaults are insufficient (e.g. date formatting, custom palettes, range limits).\n5. Include LABEL for titles when the context warrants it.\n6. Briefly explain your choices after the query.\n7. NEVER invent syntax, settings, aesthetics, layer types, or palette names not documented above.\n8. If unsure whether a feature exists, say so rather than guessing.\n9. Use `ggsql:penguins` or `ggsql:airquality` as example data when no specific data is mentioned.\n10. When the user wants to validate a query, use `ggsql validate \"<query>\"`. When the user wants to see the output, use `ggsql exec \"<query>\" -v`.","author":"@posit-dev","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/posit-dev/skills/tree/main/ggsql/ggsql","license":"MIT","category":"writing","lang":"en","tokens":4840,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[],"requires":{"mcp":[],"tools":["Bash(ggsql:*)"]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["ggsql.org"]}}