ggsql

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ggsql Query Writer

ggsql 查询编写器

ggsql combines a SQL query with a Grammar-of-Graphics visualization spec in one syntax. Write queries using ONLY the syntax below — NEVER invent clauses, settings, aesthetics, layer types, or palette names; say so if unsure whether something exists.
ggsql 将 SQL 查询与 Grammar-of-Graphics 可视化规范融合为一种语法。编写查询时只能使用以下语法——绝不要臆造子句、设置、aesthetic、图层类型或调色板名称;如果不确定某项是否存在,请明确说明。

Query structure

查询结构

Optional SQL part + required
VISUALISE
/
VISUALIZE
part.
  • SELECT → VISUALISE: last statement is a SELECT (bare,
    WITH...SELECT
    , set ops); its result feeds VISUALISE, which has no
    FROM
    .
    ggsql
    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]
  • VISUALISE FROM: VISUALISE supplies its own source (table/file/CTE/built-in), no trailing SELECT.
    ggsql
    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
Data sources (in
VISUALISE ... FROM
or
DRAW ... MAPPING ... FROM
): unquoted table/CTE (
FROM sales
), quoted file path (
FROM 'data.csv'
), built-in dataset (
FROM ggsql:penguins
,
FROM ggsql:airquality
).
可选 SQL 部分 + 必需
VISUALISE
/
VISUALIZE
部分。
  • SELECT → VISUALISE:最后一条语句是 SELECT(裸 SELECT、
    WITH...SELECT
    、集合运算);其结果输入 VISUALISE,后者没有
    FROM
    。
    ggsql
    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]
  • VISUALISE FROM:VISUALISE 自行提供数据源(表、文件、CTE 或内置数据集),末尾没有 SELECT。
    ggsql
    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
或
DRAW ... MAPPING ... FROM
中):未加引号的表或 CTE(
FROM sales
)、带引号的文件路径(
FROM 'data.csv'
)、内置数据集(
FROM ggsql:penguins
、
FROM ggsql:airquality
)。

VISUALISE clause

VISUALISE 子句

Starts the viz; optional global mappings inherited by every layer.
VISUALISE <mapping>, ... FROM <data-source>
Mapping forms: explicit
column AS aesthetic
(e.g.
revenue AS y
); implicit
column
(name = aesthetic name); wildcard
*
(all matching columns); constant
'red' AS fill
.
ggsql
VISUALISE bill_len AS x, bill_dep AS y, species AS fill FROM ggsql:penguins
VISUALISE * FROM my_table
用于开启可视化;可选的全局映射会被每个图层继承。
VISUALISE <mapping>, ... FROM <data-source>
映射形式:显式
column AS aesthetic
(例如
revenue AS y
);隐式
column
(名称即 aesthetic 名称);通配符
*
(所有匹配列);常量
'red' AS fill
。
ggsql
VISUALISE bill_len AS x, bill_dep AS y, species AS fill FROM ggsql:penguins
VISUALISE * FROM my_table

DRAW clause

DRAW 子句

Defines a layer; multiple DRAW stack bottom→top. All subclauses optional given global mappings/data.
DRAW <layer-type>
  MAPPING <mapping>, ... FROM <data-source>
  REMAPPING <stat-property> AS <aesthetic>, ...
  SETTING <param> => <value>, ...
  FILTER <condition>
  PARTITION BY <column>, ...
  ORDER BY <column>, ...
  • MAPPING — same forms as VISUALISE; merges with (layer wins over) global mappings, can add its own
    FROM
    .
    null
    blocks inheriting a global mapping:
    MAPPING null AS color
    .
  • REMAPPING — for stat layers (
    histogram
    ,
    density
    ,
    boxplot
    ,
    violin
    ,
    smooth
    ,
    bar
    w/o y): maps a computed stat to an aesthetic, e.g.
    REMAPPING density AS y
    instead of a layer's default stat.
  • SETTING — literal aesthetic values or layer params (bypasses scales), e.g.
    SETTING size => 5, stroke => 'red'
    . Position adjustment:
    'identity'
    (default, most layers),
    'stack'
    (default bar/histogram/area),
    'dodge'
    (default boxplot/violin),
    'jitter'
    .
  • FILTER — SQL WHERE condition on layer data:
    FILTER sex = 'female' AND body_mass > 4000
    .
  • PARTITION BY — extra grouping columns beyond discrete mappings:
    PARTITION BY Month
    .
  • ORDER BY — record order, matters for
    path
    :
    ORDER BY timestamp
    .
用于定义图层;多个 DRAW 从下到上叠加。给定全局映射或数据后,所有子句均为可选。
DRAW <layer-type>
  MAPPING <mapping>, ... FROM <data-source>
  REMAPPING <stat-property> AS <aesthetic>, ...
  SETTING <param> => <value>, ...
  FILTER <condition>
  PARTITION BY <column>, ...
  ORDER BY <column>, ...
  • MAPPING——与 VISUALISE 使用相同的映射形式;它会与全局映射合并(图层映射优先),也可以添加自己的
    FROM
    。
    null
    用于阻止继承对应的全局映射:
    MAPPING null AS color
    。
  • REMAPPING——用于统计图层(
    histogram
    、
    density
    、
    boxplot
    、
    violin
    、
    smooth
    、没有 y 的
    bar
    ):将计算出的统计属性映射到 aesthetic,例如使用
    REMAPPING density AS y
    替代图层的默认统计属性。
  • SETTING——设置字面值 aesthetic 或图层参数(绕过 scale),例如
    SETTING size => 5, stroke => 'red'
    。位置调整方式包括:
    'identity'
    (默认值,适用于大多数图层)、
    'stack'
    (bar、histogram、area 的默认值)、
    'dodge'
    (boxplot、violin 的默认值)、
    'jitter'
    。
  • FILTER——对图层数据应用 SQL WHERE 条件:
    FILTER sex = 'female' AND body_mass > 4000
    。
  • PARTITION BY——在离散映射之外添加额外的分组列:
    PARTITION BY Month
    。
  • ORDER BY——设置记录顺序,对
    path
    尤其重要:
    ORDER BY timestamp
    。

Aggregate (a SETTING)

聚合(一个 SETTING)

Collapses each group (
PARTITION BY
cols + discrete mappings) to one row, replacing numeric mappings with aggregated values. Layers:
point line path bar area ribbon range segment rule text tile
(not stat layers, which have their own).
ggsql
SETTING aggregate => '<spec>'                -- single
SETTING aggregate => ('<spec>', '<spec>', …) -- list
Spec is untargeted
'<func>'
(every unmapped-target numeric aesthetic; ≤2 untargeted defaults — 1st for lower-side aesthetics x/xmin/etc + all non-range layers, 2nd for upper-side xend/xmax) or targeted
'<aes>:<func>'
(overrides untargeted for that aesthetic).
Functions — reductions:
count sum prod min max range mid mean median geomean harmean rms sdev var iqr se p05–p95
; positional (need upstream
ORDER BY
):
first last diff
; band
<offset>±[<mult>]<expansion>
e.g.
'mean+1.96sdev'
(offsets:
mean median geomean harmean rms sum prod min max mid p05–p95
; expansions:
sdev se var iqr range
).
Explosion: targeting one aesthetic with multiple functions emits one row/function/group, tagged by a synthetic
aggregate
column — drive another aesthetic via
REMAPPING aggregate AS <aes>
. Equal-length exploded aesthetics run in lockstep; single-function targets repeat each row. Mixed lengths >1 error.
ggsql
-- min/max envelope as two lines per group, coloured by function
DRAW line MAPPING Date AS x, Temp AS y
  REMAPPING aggregate AS color
  SETTING aggregate => ('y:min', 'y:max')
  PARTITION BY Year
Scale interaction: for a targeted aesthetic,
SCALE BINNED
runs after aggregation (so stats aren't cancelled within a bin); untargeted
SCALE BINNED
still bins pre-aggregate to drive grouping. Continuous censoring (
SCALE <aes> FROM (lo, hi)
) and discrete OOB filtering defer to post-aggregate whenever that aesthetic is aggregated.
将每个分组(
PARTITION BY
列与离散映射)折叠为一行,并用聚合值替换数值映射。适用于以下图层:
point line path bar area ribbon range segment rule text tile
(不适用于拥有自身统计属性的 stat 图层)。
ggsql
SETTING aggregate => '<spec>'                -- single
SETTING aggregate => ('<spec>', '<spec>', …) -- list
Spec 可以是无目标的
'<func>'
(应用于每一个未映射目标的数值 aesthetic;无目标默认项最多为 2 个——第 1 个用于下侧 aesthetic(x/xmin 等)以及所有非 range 图层,第 2 个用于上侧 aesthetic(xend/xmax)),也可以是有目标的
'<aes>:<func>'
(针对该 aesthetic 覆盖无目标默认项)。
函数——归约:
count sum prod min max range mid mean median geomean harmean rms sdev var iqr se p05–p95
;位置函数(需要上游
ORDER BY
):
first last diff
;band
<offset>±[<mult>]<expansion>
,例如
'mean+1.96sdev'
(offset:
mean median geomean harmean rms sum prod min max mid p05–p95
;expansion:
sdev se var iqr range
)。
Explosion:针对一个 aesthetic 使用多个函数时,会为每个函数或分组生成一行,并使用合成的
aggregate
列进行标记;可通过
REMAPPING aggregate AS <aes>
使用该列驱动另一个 aesthetic。等长的 exploded aesthetics 会同步运行;只有单个函数的目标会重复每一行。混合长度超过 1 时会报错。
ggsql
-- min/max envelope as two lines per group, coloured by function
DRAW line MAPPING Date AS x, Temp AS y
  REMAPPING aggregate AS color
  SETTING aggregate => ('y:min', 'y:max')
  PARTITION BY Year
Scale 交互:对于有目标的 aesthetic,
SCALE BINNED
会在聚合之后运行,因此统计值不会在同一个 bin 内被抵消;无目标的
SCALE BINNED
仍会在聚合前进行分箱,以驱动分组Whenever 对应 aesthetic 已被聚合时,连续型截尾(
SCALE <aes> FROM (lo, hi)
)和离散型 OOB 过滤都会推迟到聚合后执行。

PLACE clause

PLACE 子句

Annotation layer, literal values only, no data mapping; tuples for multiple annotations.
ggsql
PLACE point SETTING x => 5, y => 10, color => 'red'
PLACE text SETTING x => (34, 44), y => (66, 49), label => ('Mean = 34', 'Mean = 44')
注释图层,仅接受字面值,不支持数据映射;可使用元组添加多个注释。
ggsql
PLACE point SETTING x => 5, y => 10, color => 'red'
PLACE text SETTING x => (34, 44), y => (66, 49), label => ('Mean = 34', 'Mean = 44')

SCALE clause

SCALE 子句

Maps data → aesthetic output; sensible defaults always apply. Only
aesthetic
is required.
SCALE <type> <aesthetic> FROM <input-range> TO <output-range> VIA <transform>
  SETTING <param> => <value>, ...
  RENAMING <value> => <label>, ...
  • Type (before aesthetic; inferred if omitted):
    CONTINUOUS
    ,
    DISCRETE
    ,
    BINNED
    (bin continuous→discrete, never auto),
    ORDINAL
    (never auto),
    IDENTITY
    (pass through, no legend).
  • Aesthetic — base name only:
    x y fill stroke color(=fill+stroke) opacity size linewidth linetype shape panel row column
    . Position families (xmin/xmax/xend/ymin/ymax/yend) scale via base name (
    SCALE x ...
    ).
  • FROM — continuous
    (min, max)
    ,
    null
    infers (
    (0, null)
    ); discrete
    ('A','B','C')
    sets order & nulls the rest, or include null explicitly.
  • TO — value array (
    ('red','blue')
    ,
    (1, 6)
    ) or named palette (
    viridis
    ,
    dark2
    ,
    tableau10
    ).
  • VIA — continuous:
    linear log log2 ln exp10 exp2 exp sqrt square asinh pseudo_log pseudo_log2 pseudo_ln integer
    ; temporal (auto for date/datetime/time cols):
    date datetime time
    ; discrete:
    string bool
    .
  • SETTING — continuous/binned:
    expand
    (factor or
    (mult,add)
    , default 0.05, x/y only),
    oob
    (
    'keep'
    default x/y,
    'censor'
    default others,
    'squish'
    ),
    breaks
    (count/array/interval string e.g.
    '2 months'
    ),
    pretty
    (bool, default true),
    reverse
    (bool). Continuous only:
    minor_breaks
    (count/array/interval string; ignored by Vega-Lite). Binned only:
    closed
    (
    'left'
    /
    'right'
    ). Discrete/ordinal:
    reverse
    .
  • RENAMING — direct + wildcard formatting (direct wins):
    RENAMING 'Adelie' => 'Pygoscelis adeliae', 'adelie' => null
    or
    RENAMING * => '{:Title}'
    (formatters:
    Title UPPER lower
    , time
    %B %Y
    , num
    %.1f
    ).
ggsql
SCALE x VIA date SETTING breaks => '2 months'
SCALE y FROM (0, 100) SETTING oob => 'squish'
SCALE BINNED x SETTING breaks => 10, pretty => false
将数据映射到 aesthetic 输出;系统始终会应用合理的默认值。仅
aesthetic
为必填项。
SCALE <type> <aesthetic> FROM <input-range> TO <output-range> VIA <transform>
  SETTING <param> => <value>, ...
  RENAMING <value> => <label>, ...
  • Type(位于 aesthetic 之前;省略时自动推断):
    CONTINUOUS
    、
    DISCRETE
    、
    BINNED
    (将连续型转换为离散型,绝不自动推断)、
    ORDINAL
    (绝不自动推断)、
    IDENTITY
    (直接传递,不生成图例)。
  • Aesthetic——仅使用基础名称:
    x y fill stroke color(=fill+stroke) opacity size linewidth linetype shape panel row column
    。位置系列(xmin/xmax/xend/ymin/ymax/yend)通过基础名称进行 scale(
    SCALE x ...
    )。
  • FROM——连续型使用
    (min, max)
    ,
    null
    表示推断(
    (0, null)
    );离散型使用
    ('A','B','C')
    设置顺序,并将其他值视为 null,也可以显式包含 null。
  • TO——值数组(
    ('red','blue')
    、
    (1, 6)
    )或命名调色板(
    viridis
    、
    dark2
    、
    tableau10
    )。
  • VIA——连续型:
    linear log log2 ln exp10 exp2 exp sqrt square asinh pseudo_log pseudo_log2 pseudo_ln integer
    ;时间型(日期、日期时间、时间列会自动推断):
    date datetime time
    ;离散型:
    string bool
    。
  • SETTING——连续型或分箱型:
    expand
    (系数或
    (mult,add)
    ,默认 0.05,仅适用于 x/y)、
    oob
    (
    'keep'
    是 x/y 的默认值,其他 aesthetic 默认
    'censor'
    ,也可使用
    'squish'
    )、
    breaks
    (数量、数组或时间间隔字符串,例如
    '2 months'
    )、
    pretty
    (布尔值,默认 true)、
    reverse
    (布尔值)。仅连续型支持:
    minor_breaks
    (数量、数组或时间间隔字符串;Vega-Lite 会忽略)。仅分箱型支持:
    closed
    (
    'left'
    /
    'right'
    )。离散型或序数型支持:
    reverse
    。
  • RENAMING——直接格式化与通配符格式化(直接格式化优先):
    RENAMING 'Adelie' => 'Pygoscelis adeliae', 'adelie' => null
    或
    RENAMING * => '{:Title}'
    (格式化器:
    Title UPPER lower
    、时间
    %B %Y
    、数字
    %.1f
    )。
ggsql
SCALE x VIA date SETTING breaks => '2 months'
SCALE y FROM (0, 100) SETTING oob => 'squish'
SCALE BINNED x SETTING breaks => 10, pretty => false

FACET clause

FACET 子句

Small multiples. 1D
FACET region
(wrap, aesthetic
panel
); 2D
FACET region BY category
(grid, aesthetics
row
/
column
). Settings:
free
(
null
default/fixed,
'x'
,
'y'
,
('x','y')
),
missing
(
'repeat'
default /
'null'
),
ncol
/
nrow
(1D only, pick one). Customize/filter via SCALE on the facet aesthetic:
ggsql
FACET region
SCALE panel RENAMING 'N' => 'North', 'S' => 'South'
FACET island
SCALE panel FROM ('Biscoe', 'Dream')   -- filters panels shown
用于分面小多图。一维形式为
FACET region
(平铺布局,使用
panel
aesthetic);二维形式为
FACET region BY category
(网格布局,使用
row
/
column
aesthetic)。设置包括:
free
(默认为
null
,表示固定,也可设为
'x'
、
'y'
或
('x','y')
)、
missing
(默认
'repeat'
,也可设为
'null'
)、
ncol
/
nrow
(仅限一维分面,二选一)。可通过对分面 aesthetic 使用 SCALE 来自定义或过滤:
ggsql
FACET region
SCALE panel RENAMING 'N' => 'North', 'S' => 'South'
FACET island
SCALE panel FROM ('Biscoe', 'Dream')   -- filters panels shown

PROJECT clause

PROJECT 子句

Coordinate system.
PROJECT <aesthetic>, ... TO <coord-type> SETTING <param> => <value>, ...
cartesian
(default): aesthetics x/y; settings
clip
(bool, default true),
ratio
(number or null).
polar
: aesthetics
radius
(primary)/
angle
(secondary); settings
clip
,
start
/
end
(degrees, default 0/start+360),
inner
(0-1 donut hole, default 0). Swap order to flip axes (
PROJECT y, x TO cartesian
); without PROJECT, type is inferred from mappings.
ggsql
PROJECT TO polar SETTING inner => 0.5   -- donut chart
用于定义坐标系。
PROJECT <aesthetic>, ... TO <coord-type> SETTING <param> => <value>, ...
cartesian
(默认)使用 x/y aesthetic;设置包括
clip
(布尔值,默认 true)、
ratio
(数值或 null)。
polar
使用
radius
(主轴)/
angle
(次轴)aesthetic;设置包括
clip
、
start
/
end
(角度,默认 0 和 start+360)、
inner
(0-1 的环形图内孔比例,默认 0)。交换顺序可翻转坐标轴(
PROJECT y, x TO cartesian
);不使用 PROJECT 时,将根据映射推断坐标系类型。
ggsql
PROJECT TO polar SETTING inner => 0.5   -- donut chart

LABEL clause

LABEL 子句

Overrides axis/legend labels & titles:
title
,
subtitle
,
caption
, or any aesthetic name;
null
suppresses.
ggsql
LABEL title => 'Sales by Region', x => 'Date', y => 'Revenue (USD)', fill => null

覆盖坐标轴或图例的标签与标题:支持
title
、
subtitle
、
caption
或任意 aesthetic 名称;
null
表示不显示。
ggsql
LABEL title => 'Sales by Region', x => 'Date', y => 'Revenue (USD)', fill => null

Layer types

图层类型

  • point — required x, y; optional size, colour, stroke, fill, opacity, shape.
  • line — required x, y; sorted by primary axis; optional colour/stroke, opacity, linewidth, linetype; settings
    position
    ,
    orientation
    (
    'aligned'
    /
    'transposed'
    ).
  • path — like line but data-order (unsorted); same aesthetics.
  • bar — auto-counts if no y; optional x, y, fill, colour, stroke; stats
    count
    ,
    proportion
    ; property
    weight
    ; settings
    position
    (default
    'stack'
    ),
    width
    . Orientation from mapping (x=vertical, y=horizontal).
  • histogram — required x; stats
    count
    ,
    density
    (default remap
    count AS <secondary>
    ); settings
    position
    (
    'stack'
    ),
    bins
    (30),
    binwidth
    ,
    closed
    .
  • density — required x; stats
    density
    ,
    intensity
    ; settings
    position
    (
    'identity'
    ),
    bandwidth
    ,
    adjust
    (1),
    kernel
    (
    'gaussian'
    default,
    epanechnikov triangular rectangular biweight cosine
    ).
  • boxplot — required x (cat), y (cont); stats
    type
    ,
    value
    ; settings
    position
    (
    'dodge'
    ),
    outliers
    (true),
    coef
    (1.5),
    width
    (0.9),
    hinge
    (points, default null/hidden).
  • violin — required x (cat), y (cont); stats
    density
    ,
    intensity
    (default remap
    density AS offset
    ); settings
    position
    (
    'dodge'
    ),
    bandwidth
    ,
    adjust
    ,
    kernel
    ,
    width
    (0.9),
    side
    (
    'both' 'left' 'bottom' 'right' 'top'
    ),
    tails
    (default 3).
  • smooth — required x, y; stat
    intensity
    ; settings
    method
    (
    'nw'
    default,
    'ols'
    ,
    'tls'
    ),
    bandwidth
    ,
    adjust
    ,
    kernel
    (nw only).
  • area — required x, y, anchored at zero; settings
    position
    (
    'stack'
    ),
    orientation
    ,
    total
    (normalize),
    center
    (steamgraph).
  • ribbon — like area but explicit ymin/ymax, unanchored.
  • segment — required x, y, xend, yend; use
    range
    instead when one coord is shared between start/end.
  • rule — required x or y (full-panel reference line); optional
    slope
    (diagonal:
    y = a + slope*x
    ).
  • text — required x, y, label; settings
    offset
    (number or
    (h,v)
    ),
    format
    (RENAMING-style interpolation),
    parse
    (bool, default true: markdown
    **bold**
    /
    *italic*
    /
    ~~strike~~
    /
    `code`
    /
    {.red span}
    ; not in Vega-Lite),
    hjust
    (
    'left' 'right' 'centre'
    or 0-1),
    vjust
    (
    'top' 'bottom' 'middle'
    or 0-1).
  • rect — pick 2 per axis from center/min/max/width/height, or just center (defaults size to 1).
  • polygon — required x, y; ordered coords; PARTITION BY separates distinct polygons.
  • range — required x, ymin, ymax; setting
    hinge
    (points, default 10, null hides).
All layers accept colour/stroke, fill, opacity, linewidth, linetype, and
position
where applicable.
  • point——必需 x、y;可选 size、colour、stroke、fill、opacity、shape。
  • line——必需 x、y;按主轴排序;可选 colour/stroke、opacity、linewidth、linetype;设置包括
    position
    、
    orientation
    (
    'aligned'
    /
    'transposed'
    )。
  • path——类似 line,但采用数据顺序(不排序);使用相同的 aesthetic。
  • bar——没有 y 时自动计数;可选 x、y、fill、colour、stroke;统计项为
    count
    、
    proportion
    ;支持
    weight
    属性;设置包括
    position
    (默认
    'stack'
    )、
    width
    。方向由映射决定(x=纵向,y=横向)。
  • histogram——必需 x;统计项为
    count
    、
    density
    (默认将
    count AS <secondary>
    重新映射);设置包括
    position
    (
    'stack'
    )、
    bins
    (30)、
    binwidth
    、
    closed
    。
  • density——必需 x;统计项为
    density
    、
    intensity
    ;设置包括
    position
    (
    'identity'
    )、
    bandwidth
    、
    adjust
    (1)、
    kernel
    (默认
    'gaussian'
    ,还支持
    epanechnikov triangular rectangular biweight cosine
    )。
  • boxplot——必需 x(分类)、y(连续型);统计项为
    type
    、
    value
    ;设置包括
    position
    (
    'dodge'
    )、
    outliers
    (true)、
    coef
    (1.5)、
    width
    (0.9)、
    hinge
    (点,默认 null/隐藏)。
  • violin——必需 x(分类)、y(连续型);统计项为
    density
    、
    intensity
    (默认将
    density AS offset
    重新映射);设置包括
    position
    (
    'dodge'
    )、
    bandwidth
    、
    adjust
    、
    kernel
    、
    width
    (0.9)、
    side
    (
    'both' 'left' 'bottom' 'right' 'top'
    )、
    tails
    (默认 3)。
  • smooth——必需 x、y;统计项为
    intensity
    ;设置包括
    method
    (默认
    'nw'
    ,还支持
    'ols'
    、
    'tls'
    )、
    bandwidth
    、
    adjust
    、
    kernel
    (仅 nw 使用)。
  • area——必需 x、y,以零为锚点;设置包括
    position
    (
    'stack'
    )、
    orientation
    、
    total
    (归一化)、
    center
    (streamgraph)。
  • ribbon——类似 area,但显式使用 ymin/ymax,不以零为锚点。
  • segment——必需 x、y、xend、yend;当起点与终点共享一个坐标时,使用
    range
    。
  • rule——必需 x 或 y(整个面板的参考线);可选
    slope
    (对角线:
    y = a + slope*x
    )。
  • text——必需 x、y、label;设置包括
    offset
    (数值或
    (h,v)
    )、
    format
    (RENAMING 风格的插值)、
    parse
    (布尔值,默认 true:支持 Markdown
    **bold**
    /
    *italic*
    /
    ~~strike~~
    /
    `code`
    /
    {.red span}
    ;Vega-Lite 不支持)、
    hjust
    (
    'left' 'right' 'centre'
    或 0-1)、
    vjust
    (
    'top' 'bottom' 'middle'
    或 0-1)。
  • rect——每个轴从 center/min/max/width/height 中选择两个,也可以只提供 center(尺寸默认为 1)。
  • polygon——必需 x、y;坐标必须有序;使用 PARTITION BY 区分不同的多边形。
  • range——必需 x、ymin、ymax;设置
    hinge
    (点,默认 10,null 表示隐藏)。
所有图层在适用情况下均支持 colour/stroke、fill、opacity、linewidth、linetype 和
position
。

Named color palettes

命名颜色调色板

  • Discrete:
    ggsql10
    (default)
    tableau10 category10 set1 set2 set3 dark2 paired pastel1 pastel2 accent kelly22
  • Sequential:
    sequential
    (default)
    viridis plasma magma inferno cividis blues greens oranges reds purples greys ylgnbu ylorbr ylorrd batlow hawaii lajolla turku
    …
  • Diverging:
    vik
    /
    diverging
    rdbu rdylbu rdylgn spectral brbg prgn piyg puor berlin roma
    …
  • Cyclic:
    romao
    /
    cyclic
    bamo broco corko viko
  • 离散型:
    ggsql10
    (默认)
    tableau10 category10 set1 set2 set3 dark2 paired pastel1 pastel2 accent kelly22
  • 顺序型:
    sequential
    (默认)
    viridis plasma magma inferno cividis blues greens oranges reds purples greys ylgnbu ylorbr ylorrd batlow hawaii lajolla turku
    ……
  • 发散型:
    vik
    /
    diverging
    rdbu rdylbu rdylgn spectral brbg prgn piyg puor berlin roma
    ……
  • 循环型:
    romao
    /
    cyclic
    bamo broco corko viko

Common patterns

常见模式

ggsql
-- Pie chart: bar layer in polar coords
VISUALISE species AS fill FROM ggsql:penguins
DRAW bar
PROJECT TO polar

-- 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 hinge => 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

-- Mean ± 1.96·sdev band per group, as a ribbon
VISUALISE Day AS x, Temp AS ymin, Temp AS ymax FROM ggsql:airquality
DRAW ribbon SETTING aggregate => ('mean-1.96sdev', 'mean+1.96sdev') PARTITION BY Month
ggsql
-- Pie chart: bar layer in polar coords
VISUALISE species AS fill FROM ggsql:penguins
DRAW bar
PROJECT TO polar

-- 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 hinge => 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

-- Mean ± 1.96·sdev band per group, as a ribbon
VISUALISE Day AS x, Temp AS ymin, Temp AS ymax FROM ggsql:airquality
DRAW ribbon SETTING aggregate => ('mean-1.96sdev', 'mean+1.96sdev') PARTITION BY Month

CLI

CLI

ggsql
subcommands:
exec <QUERY>
,
run <FILE>
,
validate <QUERY>
,
parse <QUERY>
,
view <QUERY>
(window, blocks until closed). Options:
--reader <URI>
(default
duckdb://memory
),
--writer <FORMAT>
(default
vegalite
),
--output <PATH>
(extension picks writer),
-D key=value
,
-v
. Writers:
vegalite svg pdf hep
(no GPU) and
png jpeg tiff webp
(GPU, not every build).
Don't run
ggsql view
unless a window was requested — it blocks and you can't close it; use
--output
instead. Prefer
svg
/
pdf
for pictures (no GPU adapter needed);
ggsql exec --help
lists available writers.
bash
ggsql exec "VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point" -v
ggsql exec "VISUALISE species AS fill FROM ggsql:penguins DRAW bar" -o chart.svg
ggsql
子命令:
exec <QUERY>
、
run <FILE>
、
validate <QUERY>
、
parse <QUERY>
、
view <QUERY>
(打开窗口,并会持续阻塞直至关闭)。选项:
--reader <URI>
(默认
duckdb://memory
)、
--writer <FORMAT>
(默认
vegalite
)、
--output <PATH>
(根据扩展名选择写入器)、
-D key=value
、
-v
。写入器:
vegalite svg pdf hep
(无需 GPU),以及
png jpeg tiff webp
(需要 GPU,并非每个构建版本都支持)。
除非用户明确要求打开窗口,否则不要运行
ggsql view
——它会阻塞且无法关闭;应改用
--output
。图片优先使用
svg
/
pdf
(无需 GPU 适配器);
ggsql exec --help
会列出可用的写入器。
bash
ggsql exec "VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point" -v
ggsql exec "VISUALISE species AS fill FROM ggsql:penguins DRAW bar" -o chart.svg

Reference

参考

Instructions for responding

响应说明

  1. Write a complete, valid ggsql query for the request; use SQL/CTEs before VISUALISE for data shaping.
  2. Choose the simplest layer types/settings that work; add SCALE for formatting/palettes/ranges and LABEL for titles when warranted.
  3. Briefly explain your choices after the query. Never invent syntax — say so if unsure.
  4. Default to
    ggsql:penguins
    /
    ggsql:airquality
    when no data is specified.
  5. Use
    ggsql validate "<query>"
    to validate,
    ggsql exec "<query>" -v
    to run and show output.
  1. 针对用户请求编写完整、有效的 ggsql 查询;如果需要调整数据形状,请使用 SQL/CTE 并将其放在 VISUALISE 之前。
  2. 选择能够正常工作的最简单图层类型和设置;确有需要时添加 SCALE 以设置格式、调色板或范围,并添加 LABEL 以添加标题。
  3. 在查询之后简要解释所做的选择。绝不要臆造语法——如果不确定,请明确说明。
  4. 未指定数据时,默认使用
    ggsql:penguins
    /
    ggsql:airquality
    。
  5. 使用
    ggsql validate "<query>"
    验证查询,使用
    ggsql exec "<query>" -v
    运行并显示输出。