| Title: | Lightweight Data Visualization via the Grammar of Graphics |
|---|---|
| Description: | A lightweight R interface to the AntV G2 JavaScript visualization library with a ggplot2-style API. Supports rendering in litedown, R Markdown, Quarto, Jupyter notebooks (via the R kernel), Shiny, and standalone HTML previews. |
| Authors: | Yihui Xie [aut, cre] (ORCID: <https://orcid.org/0000-0003-0645-5666>) |
| Maintainer: | Yihui Xie <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.32 |
| Built: | 2026-06-07 07:09:29 UTC |
| Source: | https://github.com/yihui/gglite |
Enables ggplot2-style + syntax for building charts. The right-hand side
must be a deferred modifier created by calling a modifier function without
a chart argument (e.g., mark_point(), theme_dark()).
## S3 method for class 'g2' e1 + e2## S3 method for class 'g2' e1 + e2
e1 |
A |
e2 |
A |
The modified g2 object.
# These two are equivalent: g2(mtcars, hp ~ mpg) |> mark_point() |> theme_dark() g2(mtcars, hp ~ mpg) + mark_point() + theme_dark()# These two are equivalent: g2(mtcars, hp ~ mpg) |> mark_point() |> theme_dark() g2(mtcars, hp ~ mpg) + mark_point() + theme_dark()
Configure animation for the most recently added mark, or the
automatically-inferred mark when none has been added explicitly. G2 supports
enter, update, and exit animations.
animate(chart = NULL, ...)animate(chart = NULL, ...)
chart |
A |
... |
Animation configuration as named lists. Use |
The modified g2 object.
# Fade-in animation on bars g2(data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)), y ~ x) |> animate(enter = list(type = 'fadeIn', duration = 1000)) # Wave-in animation g2(data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)), y ~ x) |> animate(enter = list(type = 'waveIn', duration = 800)) # Disable animation g2(mtcars, hp ~ mpg) |> animate(FALSE)# Fade-in animation on bars g2(data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)), y ~ x) |> animate(enter = list(type = 'fadeIn', duration = 1000)) # Wave-in animation g2(data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)), y ~ x) |> animate(enter = list(type = 'waveIn', duration = 800)) # Disable animation g2(mtcars, hp ~ mpg) |> animate(FALSE)
Customize the axis for a positional channel ('x' or 'y'). Set to
FALSE to hide the axis. When called immediately after a mark_*()
function (or style_mark(), labels(), etc.), the axis is applied to
that mark only, enabling per-mark axis customization for dual-axis charts.
Otherwise it applies at the chart level.
axis_(chart = NULL, channel, ...) axis_x(chart = NULL, ...) axis_y(chart = NULL, ...)axis_(chart = NULL, channel, ...) axis_x(chart = NULL, ...) axis_y(chart = NULL, ...)
chart |
A |
channel |
Positional channel: |
... |
Axis options such as |
The modified g2 object.
# Chart-level axis titles g2(mtcars, hp ~ mpg) |> axis_x(title = 'Miles per Gallon') |> axis_y(title = 'Horsepower') # Dual-axis chart: each mark gets its own axis immediately after mark_*() air = aggregate(cbind(Temp, Wind) ~ Month, data = airquality, FUN = mean) air$Month = month.abb[air$Month] g2(air, x = 'Month') |> mark_interval(encode = list(y = 'Temp')) |> scale_y(independent = TRUE) |> axis_y(title = 'Temperature (°F)') |> mark_line(encode = list(y = 'Wind')) |> scale_y(independent = TRUE) |> axis_y(position = 'right', grid = FALSE, title = 'Wind Speed (mph)')# Chart-level axis titles g2(mtcars, hp ~ mpg) |> axis_x(title = 'Miles per Gallon') |> axis_y(title = 'Horsepower') # Dual-axis chart: each mark gets its own axis immediately after mark_*() air = aggregate(cbind(Temp, Wind) ~ Month, data = airquality, FUN = mean) air$Month = month.abb[air$Month] g2(air, x = 'Month') |> mark_interval(encode = list(y = 'Temp')) |> scale_y(independent = TRUE) |> axis_y(title = 'Temperature (°F)') |> mark_line(encode = list(y = 'Wind')) |> scale_y(independent = TRUE) |> axis_y(position = 'right', grid = FALSE, title = 'Wind Speed (mph)')
Set chart dimensions, layout spacing, and renderer for a G2 chart. See https://pkg.yihui.org/gglite/examples/canvas.html for full examples.
canvas( chart = NULL, width = NULL, height = 480, padding = NULL, margin = NULL, inset = NULL, renderer = NULL, ... )canvas( chart = NULL, width = NULL, height = 480, padding = NULL, margin = NULL, inset = NULL, renderer = NULL, ... )
chart |
A |
width |
Width of the chart in pixels. |
height |
Height of the chart in pixels. Default is |
padding, margin, inset
|
Layout spacing in pixels. Each can be a scalar
(applied to all sides) or a length-4 vector |
renderer |
The rendering backend: |
... |
Additional top-level chart options passed to |
The modified g2 object (or a g2_mod when chart is NULL).
p = g2(mtcars, hp ~ mpg) p |> canvas(width = 600, height = 400) p |> canvas(padding = 30) p |> canvas(renderer = 'svg')p = g2(mtcars, hp ~ mpg) p |> canvas(width = 600, height = 400) p |> canvas(padding = 30) p |> canvas(renderer = 'svg')
Create an HTML string containing a container <div> and a <script> block
that renders the chart using G2.
chart_html(chart, id = NULL, width = NULL, height = NULL)chart_html(chart, id = NULL, width = NULL, height = NULL)
chart |
A |
id |
Optional container element ID. When |
width, height
|
Optional CSS dimensions for the container. |
The global option gglite.defer_render controls whether chart rendering is
deferred until the container scrolls into the viewport. Set
options(gglite.defer_render = TRUE) to use the default threshold (0.5,
i.e., 50% of the chart visible), or supply a numeric value between 0 and 1
to customize it, e.g., options(gglite.defer_render = 0.3). When enabled,
enter animations fire when the reader first sees each chart instead of on
page load. This is useful for demo or documentation pages. It is not
typically needed for regular plots.
A character string of HTML.
Specify the coordinate system for the chart. G2 supports these coordinate
types: 'cartesian' (default), 'polar', 'theta', 'radial', 'radar',
'helix', 'parallel'. Use the transform argument to apply coordinate
transforms such as 'transpose' (equivalent to ggplot2's coord_flip()) or
'fisheye'.
coord_(chart = NULL, type, ...) coord_polar(chart = NULL, ...) coord_theta(chart = NULL, ...) coord_radial(chart = NULL, ...) coord_radar(chart = NULL, ...) coord_helix(chart = NULL, ...) coord_parallel(chart = NULL, ...)coord_(chart = NULL, type, ...) coord_polar(chart = NULL, ...) coord_theta(chart = NULL, ...) coord_radial(chart = NULL, ...) coord_radar(chart = NULL, ...) coord_helix(chart = NULL, ...) coord_parallel(chart = NULL, ...)
chart |
A |
type |
Coordinate type string. |
... |
Additional options such as |
The 'parallel' coordinate requires a position encoding (a character
vector of column names) instead of separate x/y encodings. For radar
charts, use the 'polar' coordinate with long-format data (x/y/color).
coord_polar(): Shortcut for coord_(chart, 'polar', ...).
coord_theta(): Shortcut for coord_(chart, 'theta', ...). Used for
pie and donut charts.
coord_radial(): Shortcut for coord_(chart, 'radial', ...). Suitable
for radial bar charts.
coord_radar(): Shortcut for coord_(chart, 'radar', ...). Used with
position encoding for radar (spider) charts.
coord_helix(): Shortcut for coord_(chart, 'helix', ...).
coord_parallel(): Shortcut for coord_(chart, 'parallel', ...). Used
with position encoding for parallel coordinate plots.
The modified g2 object.
df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) p = g2(df, y ~ x, color = ~ x) # Polar coordinate (rose chart) g2(df, y ~ x) |> coord_polar() # Theta coordinate (pie / donut chart) p |> transform('stackY') |> coord_theta() p |> transform('stackY') |> coord_theta(innerRadius = 0.5) # Radial coordinate (radial bar chart) p |> coord_radial() # Parallel coordinate (uses position encoding) g2(iris, position = names(iris)[-5], color = ~ Species, padding = c(30, NA, NA, NA)) |> coord_parallel() |> legend_color(position = 'bottom') # Radar coordinate (polar with long-format data) df2 = data.frame( item = rep(c('Design', 'Dev', 'Marketing', 'Sales', 'Support'), 2), score = c(80, 90, 65, 75, 85, 60, 70, 85, 80, 70), team = rep(c('A', 'B'), each = 5) ) g2(df2, score ~ item, color = ~ team) |> mark_area(style = list(fillOpacity = 0.5)) |> mark_line(style = list(lineWidth = 2)) |> coord_polar() |> scale_x(padding = 0.5, align = 0) |> scale_y(domainMin = 0, domainMax = 100) |> axis_x(grid = TRUE)df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) p = g2(df, y ~ x, color = ~ x) # Polar coordinate (rose chart) g2(df, y ~ x) |> coord_polar() # Theta coordinate (pie / donut chart) p |> transform('stackY') |> coord_theta() p |> transform('stackY') |> coord_theta(innerRadius = 0.5) # Radial coordinate (radial bar chart) p |> coord_radial() # Parallel coordinate (uses position encoding) g2(iris, position = names(iris)[-5], color = ~ Species, padding = c(30, NA, NA, NA)) |> coord_parallel() |> legend_color(position = 'bottom') # Radar coordinate (polar with long-format data) df2 = data.frame( item = rep(c('Design', 'Dev', 'Marketing', 'Sales', 'Support'), 2), score = c(80, 90, 65, 75, 85, 60, 70, 85, 80, 70), team = rep(c('A', 'B'), each = 5) ) g2(df2, score ~ item, color = ~ team) |> mark_area(style = list(fillOpacity = 0.5)) |> mark_line(style = list(lineWidth = 2)) |> coord_polar() |> scale_x(padding = 0.5, align = 0) |> scale_y(domainMin = 0, domainMax = 100) |> axis_x(grid = TRUE)
Swap x and y axes, equivalent to ggplot2's coord_flip(). This adds a
transpose transform to the current coordinate system.
coord_transpose(chart = NULL)coord_transpose(chart = NULL)
chart |
A |
The modified g2 object.
# Horizontal bar chart (coord_flip equivalent) df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> coord_transpose()# Horizontal bar chart (coord_flip equivalent) df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> coord_transpose()
Map data columns to visual channels (x, y, color, size, shape, etc.).
Use formulas (e.g., x = ~ col) or character strings (e.g., x = 'col').
encode(chart = NULL, ...)encode(chart = NULL, ...)
chart |
A |
... |
Named mappings as |
The modified g2 object.
g2(mtcars) |> encode(x = ~ mpg, y = ~ hp)g2(mtcars) |> encode(x = ~ mpg, y = ~ hp)
Facet in a Circular Layout
facet_circle(chart = NULL, ...)facet_circle(chart = NULL, ...)
chart |
A |
... |
Facet encoding and options. Pass |
The modified g2 object.
g2(iris, Sepal.Length ~ Sepal.Width) |> facet_circle(position = ~ Species)g2(iris, Sepal.Length ~ Sepal.Width) |> facet_circle(position = ~ Species)
Split the chart into a grid of panels based on one or two variables,
similar to ggplot2's facet_grid() / facet_wrap(). Use the x and/or
y arguments to specify faceting variables. An unnamed first formula
argument is interpreted as: ~var sets x = 'var'; y ~ x sets both
x = 'x' and y = 'y'.
facet_rect(chart = NULL, ...)facet_rect(chart = NULL, ...)
chart |
A |
... |
Facet encoding and options. Pass |
The modified g2 object.
g2(iris, Sepal.Length ~ Sepal.Width) |> facet_rect(x = ~ Species) # Unnamed formula shorthand g2(iris, Sepal.Length ~ Sepal.Width) |> facet_rect(~ Species) # Two-sided formula: y ~ x df = data.frame( x = rnorm(200), y = rnorm(200), sex = sample(c('M', 'F'), 200, replace = TRUE), species = sample(c('A', 'B'), 200, replace = TRUE) ) g2(df, y ~ x) |> facet_rect(sex ~ species)g2(iris, Sepal.Length ~ Sepal.Width) |> facet_rect(x = ~ Species) # Unnamed formula shorthand g2(iris, Sepal.Length ~ Sepal.Width) |> facet_rect(~ Species) # Two-sided formula: y ~ x df = data.frame( x = rnorm(200), y = rnorm(200), sex = sample(c('M', 'F'), 200, replace = TRUE), species = sample(c('A', 'B'), 200, replace = TRUE) ) g2(df, y ~ x) |> facet_rect(sex ~ species)
Construct a base chart object, optionally with data and aesthetic mappings. Use R formulas for aesthetic mappings (see Formula Interface).
g2(data = NULL, ..., title = NULL, subtitle = NULL)g2(data = NULL, ..., title = NULL, subtitle = NULL)
data |
A data frame, a |
... |
Aesthetic mappings as |
title |
Chart title string, a convenient alternative to piping into
|
subtitle |
Chart subtitle string. |
A g2 object (S3 class).
Aesthetic mappings use R formulas as a shorthand for column names:
y ~ xSets x and y as the first positional argument.
~ xSets only x (e.g., for histograms or bar counts).
~ x1 + x2 + x3Creates a position encoding with multiple
fields (for parallel coordinates).
y ~ x | zFacets the chart by z (column direction).
y ~ x | z1 + z2Facets by z1 (columns) and z2 (rows).
color = ~ varMaps the color channel to var (one-sided
formula in a named argument). Works for any aesthetic channel.
g2(mtcars, hp ~ mpg) g2(mtcars, hp ~ mpg, color = ~ cyl) g2(mtcars, ~ mpg) # Time series g2(sunspot.year) g2(EuStockMarkets) # Title and subtitle g2(mtcars, hp ~ mpg, title = 'Motor Trend Cars', subtitle = 'mpg vs hp')g2(mtcars, hp ~ mpg) g2(mtcars, hp ~ mpg, color = ~ cyl) g2(mtcars, ~ mpg) # Time series g2(sunspot.year) g2(EuStockMarkets) # Title and subtitle g2(mtcars, hp ~ mpg, title = 'Motor Trend Cars', subtitle = 'mpg vs hp')
Create a placeholder in the UI for a G2 chart rendered by renderG2().
The required JavaScript dependencies (G2 library, column-major data helper,
and output binding) are automatically attached to the page.
g2Output(outputId, width = "100%", height = "480px")g2Output(outputId, width = "100%", height = "480px")
outputId |
Output variable name to read the chart from. |
width, height
|
CSS dimensions for the chart container. |
A Shiny UI element.
## Not run: library(shiny) ui = fluidPage(g2Output('chart1')) server = function(input, output, session) { output$chart1 = renderG2({ g2(mtcars, x = 'mpg', y = 'hp') |> mark_point() }) } shinyApp(ui, server) ## End(Not run)## Not run: library(shiny) ui = fluidPage(g2Output('chart1')) server = function(input, output, session) { output$chart1 = renderG2({ g2(mtcars, x = 'mpg', y = 'hp') |> mark_point() }) } shinyApp(ui, server) ## End(Not run)
Enable an interaction behaviour on the chart. G2 interaction types include:
'tooltip', 'elementHighlight', 'elementHighlightByX',
'elementHighlightByColor', 'elementSelect', 'elementSelectByX',
'elementSelectByColor', 'elementHoverScale', 'fisheye',
'chartIndex', 'legendFilter', 'legendHighlight',
'brushHighlight', 'brushXHighlight', 'brushYHighlight',
'brushFilter', 'brushXFilter', 'brushYFilter',
'sliderFilter', 'poptip', 'drillDown'.
interact(chart = NULL, type, ...)interact(chart = NULL, type, ...)
chart |
A |
type |
Interaction type string. |
... |
Additional interaction options. |
The modified g2 object.
# Tooltip on scatter plot g2(mtcars, hp ~ mpg) |> interact('tooltip') # Highlight elements on hover g2(mtcars, hp ~ mpg, color = ~ cyl) |> interact('elementHighlight') # Brush to highlight a region g2(mtcars, hp ~ mpg) |> interact('brushHighlight') # Legend filter g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Species) |> interact('legendFilter')# Tooltip on scatter plot g2(mtcars, hp ~ mpg) |> interact('tooltip') # Highlight elements on hover g2(mtcars, hp ~ mpg, color = ~ cyl) |> interact('elementHighlight') # Brush to highlight a region g2(mtcars, hp ~ mpg) |> interact('brushHighlight') # Legend filter g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Species) |> interact('legendFilter')
Custom Printing in Knitr
knit_print.g2(x, ...)knit_print.g2(x, ...)
x |
A |
... |
Ignored. |
A knit_asis character vector.
Append a label configuration to the most recently added mark. Can be called multiple times to add several label layers.
## S3 method for class 'g2' labels(object, text, ...) ## S3 method for class 'character' labels(object, ...) ## S3 method for class 'formula' labels(object, ...)## S3 method for class 'g2' labels(object, text, ...) ## S3 method for class 'character' labels(object, ...) ## S3 method for class 'formula' labels(object, ...)
object |
A |
text |
Label text channel: a column name as |
... |
Additional label options such as |
Use text (a column name as a formula ~col or a string 'col') to map
a data column to label text. G2 also supports innerHTML, which overrides
text when provided.
Caution when using +: S3 dispatch requires that the first argument is
unnamed. Use p + labels(~col) or p + labels('col') (not
p + labels(text = 'col')). To use innerHTML, pass a dummy first
argument: p + labels('', innerHTML = ~col). See ?labels.g2 for the full
API.
The modified g2 object (or a g2_mod when object is not a
g2).
df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> labels(text = ~ y, position = 'inside') # With + operator (first argument must be unnamed) g2(df, y ~ x) + labels(~ y) g2(df, y ~ x) + labels('y', position = 'inside')df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> labels(text = ~ y, position = 'inside') # With + operator (first argument must be unnamed) g2(df, y ~ x) + labels(~ y) g2(df, y ~ x) + labels('y', position = 'inside')
Customize the legend for a visual channel ('color', 'size', 'shape',
'opacity'). Set to FALSE to hide.
legend_(chart = NULL, channel, ...) legend_color(chart = NULL, ...) legend_size(chart = NULL, ...) legend_shape(chart = NULL, ...) legend_opacity(chart = NULL, ...)legend_(chart = NULL, channel, ...) legend_color(chart = NULL, ...) legend_size(chart = NULL, ...) legend_shape(chart = NULL, ...) legend_opacity(chart = NULL, ...)
chart |
A |
channel |
Visual channel name. |
... |
Legend options such as |
The modified g2 object.
p = g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Species) p |> legend_color(position = 'right') g2(mtcars, hp ~ mpg, size = ~ wt) |> legend_size(position = 'bottom')p = g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Species) p |> legend_color(position = 'right') g2(mtcars, hp ~ mpg, size = ~ wt) |> legend_size(position = 'bottom')
Generic function to add a mark (geometry layer) to the chart. Use the
specific mark_*() wrappers for convenience.
mark_(chart = NULL, type, ...) mark_interval(chart = NULL, ...) mark_line(chart = NULL, ...) mark_point(chart = NULL, ...) mark_area(chart = NULL, ...) mark_rect(chart = NULL, ...) mark_cell(chart = NULL, ...) mark_text(chart = NULL, ...) mark_path(chart = NULL, ...) mark_polygon(chart = NULL, ...) mark_image(chart = NULL, ...) mark_link(chart = NULL, ...) mark_line_x(chart = NULL, ...) mark_line_y(chart = NULL, ...) mark_range(chart = NULL, ...) mark_range_x(chart = NULL, ...) mark_range_y(chart = NULL, ...) mark_connector(chart = NULL, ...) mark_box(chart = NULL, ...) mark_boxplot(chart = NULL, ...) mark_beeswarm(chart, ...) mark_density(chart = NULL, ...) mark_heatmap(chart = NULL, ...) mark_vector(chart = NULL, ...) mark_node(chart = NULL, ...) mark_edge(chart = NULL, ...) mark_sankey(chart = NULL, ...) mark_chord(chart = NULL, ...) mark_treemap(chart = NULL, ...) mark_pack(chart = NULL, ...) mark_force_graph(chart = NULL, ...) mark_tree(chart = NULL, ...) mark_word_cloud(chart = NULL, ...) mark_gauge(chart = NULL, ...) mark_liquid(chart = NULL, ...) mark_shape(chart = NULL, ...) mark_sunburst(chart = NULL, ...) mark_partition(chart = NULL, ...)mark_(chart = NULL, type, ...) mark_interval(chart = NULL, ...) mark_line(chart = NULL, ...) mark_point(chart = NULL, ...) mark_area(chart = NULL, ...) mark_rect(chart = NULL, ...) mark_cell(chart = NULL, ...) mark_text(chart = NULL, ...) mark_path(chart = NULL, ...) mark_polygon(chart = NULL, ...) mark_image(chart = NULL, ...) mark_link(chart = NULL, ...) mark_line_x(chart = NULL, ...) mark_line_y(chart = NULL, ...) mark_range(chart = NULL, ...) mark_range_x(chart = NULL, ...) mark_range_y(chart = NULL, ...) mark_connector(chart = NULL, ...) mark_box(chart = NULL, ...) mark_boxplot(chart = NULL, ...) mark_beeswarm(chart, ...) mark_density(chart = NULL, ...) mark_heatmap(chart = NULL, ...) mark_vector(chart = NULL, ...) mark_node(chart = NULL, ...) mark_edge(chart = NULL, ...) mark_sankey(chart = NULL, ...) mark_chord(chart = NULL, ...) mark_treemap(chart = NULL, ...) mark_pack(chart = NULL, ...) mark_force_graph(chart = NULL, ...) mark_tree(chart = NULL, ...) mark_word_cloud(chart = NULL, ...) mark_gauge(chart = NULL, ...) mark_liquid(chart = NULL, ...) mark_shape(chart = NULL, ...) mark_sunburst(chart = NULL, ...) mark_partition(chart = NULL, ...)
chart |
A |
type |
Character string for the G2 mark type. |
... |
Mark-level options passed to G2, such as |
mark_interval(): Add an interval mark for bar and column charts.
mark_line(): Add a line mark (connects points sorted by x).
mark_point(): Add a point mark (scatter plot).
mark_area(): Add an area mark (filled region under the line).
mark_rect(): Draw rectangles. Commonly used with a bin
transform for 2-D histograms.
mark_cell(): Draw rectangular cells, commonly used for heatmaps
and calendar charts.
mark_text(): Place text labels at data coordinates.
mark_path(): Connect points in data order (unlike line, which
sorts by x).
mark_polygon(): Draw filled polygon shapes.
mark_image(): Place images at data coordinates. Requires an
src encoding for image URLs.
mark_link(): Draw links (lines) between pairs of points.
mark_line_x(): Draw a vertical reference line at a given x
position.
mark_line_y(): Draw a horizontal reference line at a given y
position.
mark_range(): Shade a rectangular region defined by x and y
intervals.
mark_range_x(): Shade a vertical band defined by an x interval.
mark_range_y(): Shade a horizontal band defined by a y interval.
mark_connector(): Draw a connector line with optional labels
between two data points.
mark_box(): Draw pre-computed box elements (for custom box
plots).
mark_boxplot(): A composite mark that automatically computes box
plot statistics (median, quartiles, whiskers) from raw data.
mark_beeswarm(): Display individual data points using force
simulation to avoid overlapping. Particularly useful for visualizing
distributions within categories.
mark_density(): Visualize probability density using kernel
density estimation (KDE). When the chart has a numeric x aesthetic, the
KDE transform and encodings are configured automatically: the density is
computed for the x column, and if color is also mapped, separate
density curves are drawn for each group. Explicit data/encode in ...
bypass this auto-configuration.
mark_heatmap(): A composite mark for rendering heatmaps from
point data.
mark_vector(): Draw arrows or vectors. Useful for wind or flow
field visualizations.
mark_node(): Used in graph visualizations together with
mark_edge().
mark_edge(): Used in graph visualizations together with
mark_node().
mark_sankey(): Draw a Sankey diagram. Data should have
source, target, and value columns.
mark_chord(): Draw a chord diagram. Data should have source,
target, and value columns.
mark_treemap(): Draw a treemap layout. Data should be
hierarchical (a nested list with name, value, and optionally
children fields).
mark_pack(): Draw a circle packing layout. Data format is the
same as mark_treemap().
mark_force_graph(): Draw a force-directed graph layout.
mark_tree(): Draw a tree layout.
mark_word_cloud(): Draw a word cloud.
mark_gauge(): Draw a gauge (speedometer) chart.
mark_liquid(): Draw a liquid fill gauge.
mark_shape(): A custom mark whose rendering is controlled by a
JavaScript render function.
mark_sunburst(): A composite mark for sunburst (radial partition)
visualization of hierarchical data. This wraps the partition mark with
polar coordinates. The data should be a nested tree structure wrapped in a
list, e.g., data = list(type = 'inline', value = list(tree)).
mark_partition(): A composite mark for hierarchical icicle chart
visualization. For a radial (sunburst) layout, use mark_sunburst()
instead. The data should be a nested tree structure wrapped in a list,
e.g., data = list(type = 'inline', value = list(tree)).
The modified g2 object.
# Bar chart df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> mark_interval() # Stacked bar chart df = data.frame( x = rep(c('A', 'B'), each = 2), y = c(3, 2, 5, 4), color = rep(c('a', 'b'), 2) ) g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('stackY') # Line and area chart df = data.frame(x = 1:5, y = c(3, 1, 4, 1, 5)) p = g2(df, y ~ x) p |> mark_line() # Scatter plot g2(mtcars, hp ~ mpg, color = ~ cyl) |> mark_point() # Area chart p |> mark_area() # 2-D histogram using bin transform g2(mtcars, hp ~ mpg) |> mark_rect( transform = list(list(type = 'bin', thresholdsX = 10, thresholdsY = 10)) ) # Heatmap cells df = expand.grid(x = LETTERS[1:4], y = LETTERS[1:4]) df$value = seq_len(nrow(df)) g2(df, y ~ x, color = ~ value) |> mark_cell() # Bar chart with text labels df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> mark_interval() |> mark_text(encode = list(text = 'y')) # Spiral path (points connected in data order) n = 100 t = seq(0, 4 * pi, length.out = n) df = data.frame(x = t * cos(t), y = t * sin(t)) g2(df, y ~ x) |> mark_path() # Triangle polygon df = data.frame(x = c(0, 1, 0.5), y = c(0, 0, 1)) g2(df, y ~ x) |> mark_polygon() # Image mark at two data points df = data.frame(x = 1:2, y = 1:2) g2(df, y ~ x) |> mark_image(style = list( src = 'https://gw.alipayobjects.com/mdn/rms_dfc253/afts/img/A*SZGfRaFPkIoAAAAAAAAAAAAAARQnAQ' )) # Link mark connecting pairs of points df = data.frame(x = c(0, 1), y = c(0, 0), x1 = c(1, 2), y1 = c(1, 1)) g2(df) |> mark_link(encode = list(x = c('x', 'x1'), y = c('y', 'y1'))) # Scatter plot with reference lines and shaded regions p = g2(mtcars, hp ~ mpg) |> mark_point() p |> mark_line_x(data = list(list(x = 20)), style = list(stroke = 'red', lineDash = c(4, 4))) p |> mark_line_y(data = list(list(y = 150)), style = list(stroke = 'red', lineDash = c(4, 4))) p |> mark_range( data = list(list(x = c(15, 25), y = c(100, 200))), style = list(fill = 'steelblue', fillOpacity = 0.15) ) p |> mark_range_x(data = list(list(x = c(15, 25))), style = list(fill = 'steelblue', fillOpacity = 0.15)) p |> mark_range_y(data = list(list(y = c(100, 200))), style = list(fill = 'orange', fillOpacity = 0.15)) # Bar chart with connector annotation df = data.frame(x = c('A', 'B'), y = c(3, 7)) g2(df, y ~ x) |> mark_interval() |> mark_connector( data = list(list(x = 'A', x1 = 'B')), encode = list(x = 'x', x1 = 'x1'), labels = list(list(text = '+133%')) ) # Box plot and beeswarm p = g2(iris, Sepal.Width ~ Species) p |> mark_boxplot() p |> mark_beeswarm() # Density plot by species g2(iris, ~ Sepal.Width, color = ~ Species) |> mark_density() # Heatmap from point data g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Petal.Length) |> mark_heatmap() # Sankey and chord diagrams df = data.frame( source = c('A', 'A', 'B'), target = c('B', 'C', 'C'), value = c(5, 3, 2) ) g2(df) |> mark_sankey( encode = list(source = 'source', target = 'target', value = 'value'), layout = list(nodeAlign = 'center') ) g2(df) |> mark_chord( encode = list(source = 'source', target = 'target', value = 'value') ) # Treemap and circle packing tree_data = list( name = 'root', children = list( list(name = 'A', value = 10), list(name = 'B', value = 20), list(name = 'C', value = 15) ) ) g2() |> mark_treemap( data = list(value = tree_data), encode = list(value = 'value') ) g2() |> mark_pack( data = list(value = tree_data), encode = list(value = 'value', color = 'name') ) # Word cloud df = data.frame( text = c('Hello', 'Data', 'Science', 'R', 'G2', 'Chart'), value = c(30, 25, 20, 15, 10, 5) ) g2(df) |> mark_word_cloud(encode = list(text = 'text', value = 'value', color = 'text')) # Liquid fill gauge g2() |> mark_liquid(data = list(list(value = 0.3)), encode = list(y = 'value'), style = list(textContent = '30%')) # Sunburst chart (hierarchical radial partition) tree = list(name = 'root', children = list( list(name = 'A', value = 10, children = list( list(name = 'A1', value = 5), list(name = 'A2', value = 5) )), list(name = 'B', value = 20) )) g2() |> mark_sunburst( data = list(type = 'inline', value = list(tree)), encode = list(value = 'value') )# Bar chart df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> mark_interval() # Stacked bar chart df = data.frame( x = rep(c('A', 'B'), each = 2), y = c(3, 2, 5, 4), color = rep(c('a', 'b'), 2) ) g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('stackY') # Line and area chart df = data.frame(x = 1:5, y = c(3, 1, 4, 1, 5)) p = g2(df, y ~ x) p |> mark_line() # Scatter plot g2(mtcars, hp ~ mpg, color = ~ cyl) |> mark_point() # Area chart p |> mark_area() # 2-D histogram using bin transform g2(mtcars, hp ~ mpg) |> mark_rect( transform = list(list(type = 'bin', thresholdsX = 10, thresholdsY = 10)) ) # Heatmap cells df = expand.grid(x = LETTERS[1:4], y = LETTERS[1:4]) df$value = seq_len(nrow(df)) g2(df, y ~ x, color = ~ value) |> mark_cell() # Bar chart with text labels df = data.frame(x = c('A', 'B', 'C'), y = c(3, 7, 2)) g2(df, y ~ x) |> mark_interval() |> mark_text(encode = list(text = 'y')) # Spiral path (points connected in data order) n = 100 t = seq(0, 4 * pi, length.out = n) df = data.frame(x = t * cos(t), y = t * sin(t)) g2(df, y ~ x) |> mark_path() # Triangle polygon df = data.frame(x = c(0, 1, 0.5), y = c(0, 0, 1)) g2(df, y ~ x) |> mark_polygon() # Image mark at two data points df = data.frame(x = 1:2, y = 1:2) g2(df, y ~ x) |> mark_image(style = list( src = 'https://gw.alipayobjects.com/mdn/rms_dfc253/afts/img/A*SZGfRaFPkIoAAAAAAAAAAAAAARQnAQ' )) # Link mark connecting pairs of points df = data.frame(x = c(0, 1), y = c(0, 0), x1 = c(1, 2), y1 = c(1, 1)) g2(df) |> mark_link(encode = list(x = c('x', 'x1'), y = c('y', 'y1'))) # Scatter plot with reference lines and shaded regions p = g2(mtcars, hp ~ mpg) |> mark_point() p |> mark_line_x(data = list(list(x = 20)), style = list(stroke = 'red', lineDash = c(4, 4))) p |> mark_line_y(data = list(list(y = 150)), style = list(stroke = 'red', lineDash = c(4, 4))) p |> mark_range( data = list(list(x = c(15, 25), y = c(100, 200))), style = list(fill = 'steelblue', fillOpacity = 0.15) ) p |> mark_range_x(data = list(list(x = c(15, 25))), style = list(fill = 'steelblue', fillOpacity = 0.15)) p |> mark_range_y(data = list(list(y = c(100, 200))), style = list(fill = 'orange', fillOpacity = 0.15)) # Bar chart with connector annotation df = data.frame(x = c('A', 'B'), y = c(3, 7)) g2(df, y ~ x) |> mark_interval() |> mark_connector( data = list(list(x = 'A', x1 = 'B')), encode = list(x = 'x', x1 = 'x1'), labels = list(list(text = '+133%')) ) # Box plot and beeswarm p = g2(iris, Sepal.Width ~ Species) p |> mark_boxplot() p |> mark_beeswarm() # Density plot by species g2(iris, ~ Sepal.Width, color = ~ Species) |> mark_density() # Heatmap from point data g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Petal.Length) |> mark_heatmap() # Sankey and chord diagrams df = data.frame( source = c('A', 'A', 'B'), target = c('B', 'C', 'C'), value = c(5, 3, 2) ) g2(df) |> mark_sankey( encode = list(source = 'source', target = 'target', value = 'value'), layout = list(nodeAlign = 'center') ) g2(df) |> mark_chord( encode = list(source = 'source', target = 'target', value = 'value') ) # Treemap and circle packing tree_data = list( name = 'root', children = list( list(name = 'A', value = 10), list(name = 'B', value = 20), list(name = 'C', value = 15) ) ) g2() |> mark_treemap( data = list(value = tree_data), encode = list(value = 'value') ) g2() |> mark_pack( data = list(value = tree_data), encode = list(value = 'value', color = 'name') ) # Word cloud df = data.frame( text = c('Hello', 'Data', 'Science', 'R', 'G2', 'Chart'), value = c(30, 25, 20, 15, 10, 5) ) g2(df) |> mark_word_cloud(encode = list(text = 'text', value = 'value', color = 'text')) # Liquid fill gauge g2() |> mark_liquid(data = list(list(value = 0.3)), encode = list(y = 'value'), style = list(textContent = '30%')) # Sunburst chart (hierarchical radial partition) tree = list(name = 'root', children = list( list(name = 'A', value = 10, children = list( list(name = 'A1', value = 5), list(name = 'A2', value = 5) )), list(name = 'B', value = 20) )) g2() |> mark_sunburst( data = list(type = 'inline', value = list(tree)), encode = list(value = 'value') )
Preview a Chart in the Viewer or Browser
## S3 method for class 'g2' print(x, ...)## S3 method for class 'g2' print(x, ...)
x |
A |
... |
Additional arguments passed to |
The chart object (invisibly).
Create a reactive G2 chart for use with g2Output().
Assign it to an output slot: output$ID = renderG2({...}).
renderG2(expr, env = parent.frame(), quoted = FALSE)renderG2(expr, env = parent.frame(), quoted = FALSE)
expr |
An expression that returns a |
env |
The environment in which to evaluate |
quoted |
Whether |
A render function for use with g2Output().
Add or modify scale settings for a given aesthetic channel. When called
immediately after a mark_*() function (or after style_mark(),
labels(), etc. that target the last mark), the scale is applied to that
mark only. Otherwise it is applied at the chart level and affects all marks.
This context-sensitivity enables dual-axis charts: pipe scale_y() right
after each mark to give it its own independent y scale.
scale_(chart = NULL, field, ...) scale_x(chart = NULL, ...) scale_y(chart = NULL, ...) scale_color(chart = NULL, ...) scale_size(chart = NULL, ...) scale_shape(chart = NULL, ...) scale_opacity(chart = NULL, ...)scale_(chart = NULL, field, ...) scale_x(chart = NULL, ...) scale_y(chart = NULL, ...) scale_color(chart = NULL, ...) scale_size(chart = NULL, ...) scale_shape(chart = NULL, ...) scale_opacity(chart = NULL, ...)
chart |
A |
field |
Character string naming the channel (e.g., |
... |
Scale options passed to G2 (e.g., |
G2 scale types: 'linear', 'ordinal', 'band', 'point', 'time',
'log', 'pow', 'sqrt', 'threshold', 'quantize', 'quantile',
'sequential', 'identity', 'constant'.
The modified g2 object.
p = g2(mtcars, hp ~ mpg) # Log-scaled x axis p |> scale_x(type = 'log') # Square-root y axis p |> scale_y(type = 'sqrt') # Ordinal color palette g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Species) |> scale_color(palette = 'category10')p = g2(mtcars, hp ~ mpg) # Log-scaled x axis p |> scale_x(type = 'log') # Square-root y axis p |> scale_y(type = 'sqrt') # Ordinal color palette g2(iris, Sepal.Length ~ Sepal.Width, color = ~ Species) |> scale_color(palette = 'category10')
Add a scrollbar to a positional channel for zooming/panning.
scroll_(chart = NULL, channel, ...) scroll_x(chart = NULL, ...) scroll_y(chart = NULL, ...)scroll_(chart = NULL, channel, ...) scroll_x(chart = NULL, ...) scroll_y(chart = NULL, ...)
chart |
A |
channel |
Positional channel: |
... |
Scrollbar options. |
The modified g2 object.
df = data.frame(x = 1:100, y = cumsum(rnorm(100))) p = g2(df, y ~ x) |> mark_line() p |> scroll_x() |> scroll_y()df = data.frame(x = 1:100, y = cumsum(rnorm(100))) p = g2(df, y ~ x) |> mark_line() p |> scroll_x() |> scroll_y()
Add a range slider to a positional channel for zooming/panning.
slider_(chart = NULL, channel, ...) slider_x(chart = NULL, ...) slider_y(chart = NULL, ...)slider_(chart = NULL, channel, ...) slider_x(chart = NULL, ...) slider_y(chart = NULL, ...)
chart |
A |
channel |
Positional channel: |
... |
Slider options. |
The modified g2 object.
p = g2(mtcars, hp ~ mpg) p |> slider_x() |> slider_y()p = g2(mtcars, hp ~ mpg) p |> slider_x() |> slider_y()
Set Style on the Last Mark
style_mark(chart = NULL, ...)style_mark(chart = NULL, ...)
chart |
A |
... |
Style options such as |
The modified g2 object.
g2(mtcars, hp ~ mpg) |> style_mark(fill = 'steelblue', stroke = 'white', lineWidth = 1)g2(mtcars, hp ~ mpg) |> style_mark(fill = 'steelblue', stroke = 'white', lineWidth = 1)
G2 built-in themes: 'classic' (default), 'classicDark', 'light',
'dark', 'academy'.
theme_(chart = NULL, type, ...) theme_classic(chart = NULL, ...) theme_classic_dark(chart = NULL, ...) theme_light(chart = NULL, ...) theme_dark(chart = NULL, ...) theme_academy(chart = NULL, ...)theme_(chart = NULL, type, ...) theme_classic(chart = NULL, ...) theme_classic_dark(chart = NULL, ...) theme_light(chart = NULL, ...) theme_dark(chart = NULL, ...) theme_academy(chart = NULL, ...)
chart |
A |
type |
Theme name string or a list of custom theme options. Use the
specific wrappers ( |
... |
Additional theme options merged with the type. |
To set global theme options for all charts, use options(gglite.theme = list(...)). This is useful for changing default font sizes, grid line
visibility, and other theme properties without modifying each chart
individually. For example:
options(gglite.theme = list( title = list(titleFontSize = 20), axis = list(labelFontSize = 16, gridStrokeOpacity = 0.3), legendCategory = list(itemLabelFontSize = 14) ))
Per-chart theme_() settings are merged on top of the global option.
The modified g2 object.
p = g2(mtcars, hp ~ mpg) p |> theme_classic() p |> theme_dark() p |> theme_academy()p = g2(mtcars, hp ~ mpg) p |> theme_classic() p |> theme_dark() p |> theme_academy()
Set the chart title and subtitle, as well as their styles.
titles(chart = NULL, main, ...)titles(chart = NULL, main, ...)
chart |
A |
main |
Title text string. |
... |
Additional title options such as |
The modified g2 object.
g2(mtcars, hp ~ mpg) |> titles('Motor Trend Cars', subtitle = 'mpg vs hp')g2(mtcars, hp ~ mpg) |> titles('Motor Trend Cars', subtitle = 'mpg vs hp')
Configure tooltip interaction behavior. All options are applied to
interaction.tooltip in the G2 spec: pass FALSE to disable the tooltip,
or pass named options such as crosshairs, shared, marker, and any
crosshairs*/marker* style properties. To configure the data displayed in
a tooltip for a specific mark (e.g., channel, valueFormatter, items),
pass a tooltip list argument directly to the mark function instead, e.g.,
mark_line(tooltip = list(channel = 'y', valueFormatter = '.0%')).
tooltip(chart = NULL, ...)tooltip(chart = NULL, ...)
chart |
A |
... |
Tooltip interaction options such as |
The modified g2 object.
# Enable crosshairs (works best with line/area marks which use series tooltip) df = data.frame(x = 1:6, y = c(3, 1, 4, 1, 5, 2)) g2(df, y ~ x) |> mark_line() |> tooltip(crosshairs = TRUE) # Shared tooltip for multi-series line chart df2 = data.frame( x = rep(1:5, 2), y = c(3, 1, 4, 1, 5, 2, 7, 1, 8, 3), group = rep(c('A', 'B'), each = 5) ) g2(df2, y ~ x, color = ~ group) |> mark_line() |> tooltip(shared = TRUE) # Disable tooltip g2(mtcars, hp ~ mpg) |> tooltip(FALSE)# Enable crosshairs (works best with line/area marks which use series tooltip) df = data.frame(x = 1:6, y = c(3, 1, 4, 1, 5, 2)) g2(df, y ~ x) |> mark_line() |> tooltip(crosshairs = TRUE) # Shared tooltip for multi-series line chart df2 = data.frame( x = rep(1:5, 2), y = c(3, 1, 4, 1, 5, 2, 7, 1, 8, 3), group = rep(c('A', 'B'), each = 5) ) g2(df2, y ~ x, color = ~ group) |> mark_line() |> tooltip(shared = TRUE) # Disable tooltip g2(mtcars, hp ~ mpg) |> tooltip(FALSE)
Append a data transform to the most recently added mark. G2 transforms
correspond roughly to ggplot2's stat_*() and position_*() functions.
## S3 method for class 'g2' transform(`_data`, type, ...) ## S3 method for class 'character' transform(`_data`, ...)## S3 method for class 'g2' transform(`_data`, type, ...) ## S3 method for class 'character' transform(`_data`, ...)
_data |
A |
type |
Transform type string (e.g., |
... |
Additional transform options (e.g., |
Common transforms: 'stackY' (stack, like position_stack()), 'dodgeX'
(dodge, like position_dodge()), 'normalizeY' (normalize to 100%, like
position_fill()), 'jitterX' / 'jitterY' (jitter, like
position_jitter()), 'bin' / 'binX' (bin data, like stat_bin()),
'groupX' / 'groupY' / 'groupColor' (group and aggregate, like
stat_summary()), 'sortX' / 'sortY' / 'sortColor' (sort data),
'symmetryY' (mirror, for pyramid / funnel charts), 'diffY' (difference,
for waterfall charts), 'select' / 'selectX' / 'selectY' (filter),
'sample' (down-sample), 'pack' (circle-packing layout), 'flexX'
(flexible x spacing, Marimekko charts).
Caution when using +: S3 dispatch requires that the first argument is
unnamed. Use p + transform('stackY') (not
p + transform(type = 'stackY')). See ?transform.g2 for the full API.
The modified g2 object (or a g2_mod when _data is a string).
# Stacked bar chart df = data.frame( x = rep(c('A', 'B'), each = 2), y = c(3, 2, 5, 4), color = rep(c('a', 'b'), 2) ) g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('stackY') # Grouped (dodged) bar chart g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('dodgeX') # Percent stacked bar (normalizeY + stackY) g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('stackY') |> transform('normalizeY') # Jitter on a scatter plot g2(mtcars, hp ~ cyl) |> transform('jitterX') # Histogram using binX g2(mtcars, ~ mpg) |> mark_interval(encode = list(y = 'count')) |> transform('binX', thresholds = 15) # With + operator (first argument must be unnamed) g2(df, y ~ x, color = ~ color) |> mark_interval() + transform('stackY')# Stacked bar chart df = data.frame( x = rep(c('A', 'B'), each = 2), y = c(3, 2, 5, 4), color = rep(c('a', 'b'), 2) ) g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('stackY') # Grouped (dodged) bar chart g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('dodgeX') # Percent stacked bar (normalizeY + stackY) g2(df, y ~ x, color = ~ color) |> mark_interval() |> transform('stackY') |> transform('normalizeY') # Jitter on a scatter plot g2(mtcars, hp ~ cyl) |> transform('jitterX') # Histogram using binX g2(mtcars, ~ mpg) |> mark_interval(encode = list(y = 'count')) |> transform('binX', thresholds = 15) # With + operator (first argument must be unnamed) g2(df, y ~ x, color = ~ color) |> mark_interval() + transform('stackY')