| Title: | Create D3 Based SVG Graphics |
|---|---|
| Description: | Create 'D3' based 'SVG' ('Scalable Vector Graphics') graphics using a simple 'R' API. The package aims to simplify the creation of many 'SVG' plot types using a straightforward 'R' API. The package relies on the 'r2d3' 'R' package and the 'D3' 'JavaScript' library. See <https://rstudio.github.io/r2d3/> and <https://d3js.org/> respectively. |
| Authors: | Mohamed El Fodil Ihaddaden [aut, cre], June Choe [ctb, cph], Mike Bostock [ctb, cph] (D3.js developer), RStudio [ctb, cph] (developers of the r2d3 package) |
| Maintainer: | Mohamed El Fodil Ihaddaden <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.0.0 |
| Built: | 2026-11-20 14:56:34 UTC |
| Source: | https://github.com/feddelegrand7/ddplot |
Create an animated line chart
anim_line_chart( data, x, y, curve = "curveLinear", duration = 5000, stroke = "crimson", stroke_width = 1.5, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 16, y_title = NULL, y_title_font_size = 16, title = NULL, title_font_size = 22, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "#CAD0D3", opacity = 1, axis_col = "black", width = NULL, height = NULL )anim_line_chart( data, x, y, curve = "curveLinear", duration = 5000, stroke = "crimson", stroke_width = 1.5, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 16, y_title = NULL, y_title_font_size = 16, title = NULL, title_font_size = 22, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "#CAD0D3", opacity = 1, axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
x |
The x-variable to consider. Must be a date variable in 'yyyy-mm-dd' format. |
y |
The y-variable to consider. |
curve |
Optional. The line's curve type to render. A complete list can be found here <https://github.com/d3/d3-shape#curves>. Defaults to 'curveLinear'. |
duration |
The duration in Milliseconds of the animation. Defaults to 5000. |
stroke |
The color of the line. Defaults to 'crimson'. |
stroke_width |
The width of the line. Defaults to 1.5. |
x_ticks |
Optional. the number of x-axis ticks to consider. |
y_ticks |
Optional. The number of y-axis ticks to consider. |
x_title |
Optional. The title of the x-axis. |
x_title_font_size |
The font size of the x-axis title. Defaults to 16. |
y_title |
Optional. The title of the y-axis. |
y_title_font_size |
The font size of the y-axis title. Defaults to 16. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 22. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "#CAD0D3" HEX color. |
opacity |
The color opacity of the bars (from 0 to 1). Defaults to 1. |
axis_col |
the color of the x and y axis. It includes the ticks, the labels and titles. Defaults to 'black'. |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An animated SVG line chart.
airpassengers <- data.frame( passengers = as.matrix(AirPassengers), date= zoo::as.Date(time(AirPassengers)) ) anim_line_chart( data = airpassengers, x = "date", y = "passengers", duration = 10000 # in milliseconds (10 seconds) )airpassengers <- data.frame( passengers = as.matrix(AirPassengers), date= zoo::as.Date(time(AirPassengers)) ) anim_line_chart( data = airpassengers, x = "date", y = "passengers", duration = 10000 # in milliseconds (10 seconds) )
Create an animated histogram.
animated_histogram( x, bins = 30, duration = 2000, delay = 100, fill = "crimson", x_font_size = 10, y_font_size = 10, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 16, y_title = NULL, y_title_font_size = 16, title = NULL, title_font_size = 22, stroke = "crimson", stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "#CAD0D3", opacity = 1, axis_col = "black", width = NULL, height = NULL )animated_histogram( x, bins = 30, duration = 2000, delay = 100, fill = "crimson", x_font_size = 10, y_font_size = 10, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 16, y_title = NULL, y_title_font_size = 16, title = NULL, title_font_size = 22, stroke = "crimson", stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "#CAD0D3", opacity = 1, axis_col = "black", width = NULL, height = NULL )
x |
A vector of data. |
bins |
The number of bins to consider. Defaults to 30. |
duration |
The duration of the bars' transition in milliseconds. Defaults to 2000. |
delay |
The amount of time (in milliseconds) that precedes before triggering the appearance of each bar. Defaults to 100. |
fill |
The color of the bars. Defaults to 'crimson'. |
x_font_size |
the font size of the x-axis labels. Defaults to 10. |
y_font_size |
the font size of the y-axis labels. Defaults to 10. |
x_ticks |
Optional. the number of x-axis ticks to consider. |
y_ticks |
Optional. The number of y-axis ticks to consider. |
x_title |
Optional. The title of the x-axis. |
x_title_font_size |
The font size of the x-axis title. Defaults to 16. |
y_title |
Optional. The title of the y-axis. |
y_title_font_size |
The font size of the y-axis title. Defaults to 16. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 22. |
stroke |
The stroke color of the bars. Defaults to 'crimson'. |
stroke_width |
Optional. the stroke width of the bars. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "#CAD0D3" HEX color. |
opacity |
The color opacity of the bars (from 0 to 1). Defaults to 1. |
axis_col |
the color of the x and y axis. It includes the ticks, the labels and titles. Defaults to 'black'. |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An animated SVG histogram.
animated_histogram( x = mtcars$mpg, duration = 2000, delay = 100 )animated_histogram( x = mtcars$mpg, duration = 2000, delay = 100 )
Draws a shaded band between a lower and an upper value over time, such as
a daily minimum and maximum, a confidence or forecast interval, or a
target range, optionally with a central line (y, for example the
mean or the median). With group, one band per group is drawn. It
shares the interactions of line_chart(): a crosshair tooltip
showing each band's range, range buttons, a navigator, drag-to-zoom
(double-click to reset) and a clickable legend.
area_band( data, x, y_lower, y_upper, fill = NULL, stroke = NULL, stroke_width = NULL, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = NULL, axis_col = "#333333", width = NULL, height = NULL, y = NULL, group = NULL, line_width = 2, curve = "curveLinear", y_zero = FALSE, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, grid_col = "#e9e9e9" )area_band( data, x, y_lower, y_upper, fill = NULL, stroke = NULL, stroke_width = NULL, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = NULL, axis_col = "#333333", width = NULL, height = NULL, y = NULL, group = NULL, line_width = 2, curve = "curveLinear", y_zero = FALSE, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, grid_col = "#e9e9e9" )
data |
A data frame, or a |
x |
The time variable: a |
y_lower |
The column holding the lower bound of the band. |
y_upper |
The column holding the upper bound of the band. |
fill |
The colour of the band (and of the central line). A single colour, or one colour per group (a named vector maps colours to groups). Defaults to a built-in palette. |
stroke |
Optional. The colour of the band's outline. Without
|
stroke_width |
Optional. The width of the band's outline. Defaults to 1. |
x_ticks |
Optional. The approximate number of x-axis ticks. |
y_ticks |
Optional. The approximate number of y-axis ticks. |
x_title |
Optional. The title of the x-axis. |
x_title_font_size |
The font size of the x-axis title. Defaults to 13. |
y_title |
Optional. The title of the y-axis, shown above the axis. |
y_title_font_size |
The font size of the y-axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
opacity |
Optional. The opacity of the band (from 0 to 1). Defaults to 0.3, or 0.22 with a central line. |
axis_col |
The color of the axis text, ticks and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
y |
Optional. A column drawn as a line inside the band. |
group |
Optional. The column whose values name the bands (one band per value, long data). |
line_width |
The width of the central line. Defaults to 2. |
curve |
The line's curve type. A complete list can be found here <https://github.com/d3/d3-shape#curves>. Defaults to 'curveLinear'; 'curveMonotoneX' gives smooth lines that never overshoot the data. |
y_zero |
Logical. Force the y axis to include 0. Defaults to
|
events |
Optional. Dates to mark with a vertical line: either a vector of dates (names are used as labels) or a data frame whose first column holds the dates and whose second column (optional) holds labels. |
bands |
Optional. Periods to shade, as a data frame whose first two columns are the start and end dates. An optional third column holds the labels and an optional fourth column the fill colors. |
h_lines |
Optional. Numeric reference values drawn as horizontal
dashed lines (names are used as labels). Only drawn when
|
legend |
Logical. Show the interactive legend (click to hide or show
a series, double-click to isolate it). When |
end_labels |
Logical. Label each line at its last visible point. When
|
tooltip |
Logical. Show the crosshair and the tooltip on hover.
Defaults to |
navigator |
Logical. Show the navigator (a miniature of the full
series with a brush to select the visible range) under the chart.
Defaults to |
range_buttons |
Logical. Show range buttons (1M, 6M, YTD, 1Y, 5Y,
All, ...), chosen from the length and frequency of the data. Only used
with dates. Defaults to |
zoom |
Logical. Drag horizontally on the chart to zoom into a range;
double-click to reset. Defaults to |
animate |
Logical. Draw the lines in with an animation on first
render. Defaults to |
value_format |
Optional. A d3-format string for values in the tooltip
(see <https://github.com/d3/d3-format>). Defaults to ",.2~f", or "+.2~%"
with |
value_prefix, value_suffix
|
Optional. Text placed before and after the values on the y axis and in the tooltip, for example "$" or " km". |
date_format |
Optional. A d3-time-format string for the date in the
tooltip (see <https://github.com/d3/d3-time-format>). When |
subtitle |
Optional. A subtitle shown under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
x_font_size, y_font_size
|
The font size of the axis tick labels. Defaults to 11. |
grid_col |
The color of the horizontal grid lines. Defaults to "#e9e9e9". |
An interactive SVG band chart.
airpassengers <- data.frame( passengers_lower = as.matrix(AirPassengers), passengers_upper = as.matrix(AirPassengers) + 40, date = zoo::as.Date(time(AirPassengers)) ) area_band( data = airpassengers, x = "date", y_lower = "passengers_lower", y_upper = "passengers_upper", fill = "#efb118", stroke = "#9c6b4e" ) # A band around a central line, one band per group set.seed(1) days <- seq(as.Date("2026-01-01"), by = "day", length.out = 120) temps <- do.call(rbind, lapply(c("Oslo", "Madrid"), function(city) { base <- if (city == "Oslo") -2 else 9 mid <- base + 8 * sin(seq_along(days) / 38) + rnorm(120, 0, 1) data.frame(date = days, city = city, mean = mid, low = mid - runif(120, 2, 5), high = mid + runif(120, 2, 5)) })) area_band( temps, x = "date", y_lower = "low", y_upper = "high", y = "mean", group = "city", value_format = ".1f", value_suffix = " °C", title = "Daily temperatures", subtitle = "Mean, with the daily minimum and maximum" )airpassengers <- data.frame( passengers_lower = as.matrix(AirPassengers), passengers_upper = as.matrix(AirPassengers) + 40, date = zoo::as.Date(time(AirPassengers)) ) area_band( data = airpassengers, x = "date", y_lower = "passengers_lower", y_upper = "passengers_upper", fill = "#efb118", stroke = "#9c6b4e" ) # A band around a central line, one band per group set.seed(1) days <- seq(as.Date("2026-01-01"), by = "day", length.out = 120) temps <- do.call(rbind, lapply(c("Oslo", "Madrid"), function(city) { base <- if (city == "Oslo") -2 else 9 mid <- base + 8 * sin(seq_along(days) / 38) + rnorm(120, 0, 1) data.frame(date = days, city = city, mean = mid, low = mid - runif(120, 2, 5), high = mid + runif(120, 2, 5)) })) area_band( temps, x = "date", y_lower = "low", y_upper = "high", y = "mean", group = "city", value_format = ".1f", value_suffix = " °C", title = "Daily temperatures", subtitle = "Mean, with the daily minimum and maximum" )
An area chart for time series: the area under the line is filled with a
soft gradient. It shares the interactions of line_chart():
a crosshair tooltip, range buttons (1M, 6M, YTD, 1Y, ...), a navigator
with a brush under the chart, drag-to-zoom (double-click to reset) and,
with several series, a clickable legend and labels at the end of each
area.
area_chart( data, x = NULL, y = NULL, fill = NULL, stroke = NULL, stroke_width = 2, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = NULL, axis_col = "#333333", width = NULL, height = NULL, group = NULL, baseline = NULL, negative_fill = NULL, curve = "curveLinear", points = FALSE, y_zero = NULL, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, grid_col = "#e9e9e9" )area_chart( data, x = NULL, y = NULL, fill = NULL, stroke = NULL, stroke_width = 2, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = NULL, axis_col = "#333333", width = NULL, height = NULL, group = NULL, baseline = NULL, negative_fill = NULL, curve = "curveLinear", points = FALSE, y_zero = NULL, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, grid_col = "#e9e9e9" )
data |
A data frame, or a |
x |
The time variable: a |
y |
The value variable(s): one column name, or several to draw one area per column. |
fill |
The colour of the area (and of its line). A single colour, or one colour per series (a named vector maps colours to series). Defaults to a built-in palette. |
stroke |
Optional. The colour of the line on top of the area. Defaults to the colour of the area. |
stroke_width |
The width of the line on top of the area. Defaults to 2; use 0 to hide the line. |
x_ticks |
Optional. The approximate number of x-axis ticks. |
y_ticks |
Optional. The approximate number of y-axis ticks. |
x_title |
Optional. The title of the x-axis. |
x_title_font_size |
The font size of the x-axis title. Defaults to 13. |
y_title |
Optional. The title of the y-axis, shown above the axis. |
y_title_font_size |
The font size of the y-axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
opacity |
Optional. The opacity of the area fill (from 0 to 1). When
|
axis_col |
The color of the axis text, ticks and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
group |
Optional. For long data, the column whose values name the series (one area per value). |
baseline |
Optional. A number: the area is drawn between the line and this value instead of zero. |
negative_fill |
Optional. With |
curve |
The line's curve type. A complete list can be found here <https://github.com/d3/d3-shape#curves>. Defaults to 'curveLinear'; 'curveMonotoneX' gives smooth lines that never overshoot the data. |
points |
Logical. Draw a marker on every data point. Defaults to
|
y_zero |
Logical. Force the y axis to include 0. When |
events |
Optional. Dates to mark with a vertical line: either a vector of dates (names are used as labels) or a data frame whose first column holds the dates and whose second column (optional) holds labels. |
bands |
Optional. Periods to shade, as a data frame whose first two columns are the start and end dates. An optional third column holds the labels and an optional fourth column the fill colors. |
h_lines |
Optional. Numeric reference values drawn as horizontal
dashed lines (names are used as labels). Only drawn when
|
legend |
Logical. Show the interactive legend (click to hide or show
a series, double-click to isolate it). When |
end_labels |
Logical. Label each line at its last visible point. When
|
tooltip |
Logical. Show the crosshair and the tooltip on hover.
Defaults to |
navigator |
Logical. Show the navigator (a miniature of the full
series with a brush to select the visible range) under the chart.
Defaults to |
range_buttons |
Logical. Show range buttons (1M, 6M, YTD, 1Y, 5Y,
All, ...), chosen from the length and frequency of the data. Only used
with dates. Defaults to |
zoom |
Logical. Drag horizontally on the chart to zoom into a range;
double-click to reset. Defaults to |
animate |
Logical. Draw the lines in with an animation on first
render. Defaults to |
value_format |
Optional. A d3-format string for values in the tooltip
(see <https://github.com/d3/d3-format>). Defaults to ",.2~f", or "+.2~%"
with |
value_prefix, value_suffix
|
Optional. Text placed before and after the values on the y axis and in the tooltip, for example "$" or " km". |
date_format |
Optional. A d3-time-format string for the date in the
tooltip (see <https://github.com/d3/d3-time-format>). When |
subtitle |
Optional. A subtitle shown under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
x_font_size, y_font_size
|
The font size of the axis tick labels. Defaults to 11. |
grid_col |
The color of the horizontal grid lines. Defaults to "#e9e9e9". |
With baseline, the area is drawn between the line and that value
instead of zero, and negative_fill colours the part below it, which
suits anomalies, balances or profit and loss.
The data can be one column (y = "value"), several columns
(y = c("a", "b")), long data with a group column, or a
ts / mts object passed directly as data. Several
series are drawn on top of each other; use
stacked_area_chart() to stack them.
An interactive SVG area chart.
# A ts object can be passed directly area_chart(AirPassengers, y = "passengers", title = "Airline passengers") # The classic data frame interface still works airpassengers <- data.frame( passengers = as.matrix(AirPassengers), date = zoo::as.Date(time(AirPassengers)) ) area_chart( data = airpassengers, x = "date", y = "passengers", fill = "purple" ) # Above and below a baseline library(ggplot2) # for the economics data set area_chart( economics, x = "date", y = "psavert", baseline = mean(economics$psavert), fill = "#3ca951", negative_fill = "#ff725c", value_suffix = "%", title = "US personal savings rate", subtitle = "Above and below its long-run average" )# A ts object can be passed directly area_chart(AirPassengers, y = "passengers", title = "Airline passengers") # The classic data frame interface still works airpassengers <- data.frame( passengers = as.matrix(AirPassengers), date = zoo::as.Date(time(AirPassengers)) ) area_chart( data = airpassengers, x = "date", y = "passengers", fill = "purple" ) # Above and below a baseline library(ggplot2) # for the economics data set area_chart( economics, x = "date", y = "psavert", baseline = mean(economics$psavert), fill = "#3ca951", negative_fill = "#ff725c", value_suffix = "%", title = "US personal savings rate", subtitle = "Above and below its long-run average" )
Draws one bar per category, or, with group, grouped, stacked or
100% stacked bars. The data can be one row per bar, or raw rows that are
aggregated for you (agg); leave y empty to count rows. Bars
grow in when the chart is drawn, show their values, and can be re-sorted
and re-arranged from the chart itself.
bar_chart( data, x, y = NULL, fill = NULL, sort = "none", padding_width = 0.2, x_ticks = NULL, x_font_size = 11, y_font_size = 11, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 1, axis_col = "#333333", width = NULL, height = NULL, group = NULL, position = c("grouped", "stacked", "percent"), agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, corner_radius = 3, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )bar_chart( data, x, y = NULL, fill = NULL, sort = "none", padding_width = 0.2, x_ticks = NULL, x_font_size = 11, y_font_size = 11, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 1, axis_col = "#333333", width = NULL, height = NULL, group = NULL, position = c("grouped", "stacked", "percent"), agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, corner_radius = 3, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )
data |
The data frame containing the variables to consider. |
x |
The name of the categorical variable (one bar per value). |
y |
The name of the numeric variable. When |
fill |
The colour of the bars. A single colour, or, without
|
sort |
The initial order of the bars: |
padding_width |
The space between bars, from 0 to 0.99. Defaults to 0.2. |
x_ticks |
Not used; kept for compatibility. |
x_font_size |
The font size of the category labels. Defaults to 11. |
y_font_size |
The font size of the value axis labels. Defaults to 11. |
y_ticks |
Optional. The approximate number of value axis ticks. |
x_title |
Optional. The title of the category axis. |
x_title_font_size |
The font size of the category axis title. Defaults to 13. |
y_title |
Optional. The title of the value axis, drawn above it.
Defaults to the name of |
y_title_font_size |
The font size of the value axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
stroke |
Optional. The stroke colour of the bars. |
stroke_width |
Optional. The stroke width of the bars. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
opacity |
The opacity of the bars (from 0 to 1). Defaults to 1. |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
group |
Optional. The name of a column that splits each bar into groups (one colour per group, with a clickable legend). |
position |
How groups are drawn: |
agg |
How rows with the same category (and group) are combined:
|
labels |
Logical. Write the values on the bars (labels that do not fit
are skipped). Defaults to |
highlight |
Optional. A character vector of categories to emphasise;
the other bars are drawn in grey (or faded, with |
ref_lines |
Optional. Numeric values drawn as dashed reference lines across the bars (e.g. a target or an average); names are used as labels. |
negative_fill |
Optional. The colour of negative bars (without
|
corner_radius |
The radius of the rounded bar ends, in pixels. Defaults to 3; use 0 for square bars. |
legend |
Logical. Show the legend. When |
controls |
Logical. Show the layout and sort buttons. Defaults to
|
tooltip |
Logical. Show a tooltip on hover. Defaults to |
animate |
Logical. Animate the bars when the chart is first drawn.
Defaults to |
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
grid_col |
The colour of the grid lines. Defaults to "#e9e9e9"; use
|
An interactive SVG bar chart (an r2d3 htmlwidget).
Hover a bar to see its value, its share of the total and its rank;
with group, the tooltip lists every group for that category.
The buttons at the top right switch between grouped, stacked and
100% bars (with group) and between the original order, largest
first and smallest first.
Click a legend entry to hide or show a group, double-click it to isolate it. Hovering a legend entry highlights the group.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a bar sets input$id_clicked to a list with the
category and group of the bar. The layout, the sort order and
the hidden groups are kept when the chart is re-rendered.
library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for data wrangling mpg %>% group_by(manufacturer) %>% summarise(mean_cty = mean(cty)) %>% bar_chart( x = "manufacturer", y = "mean_cty", sort = "descending", y_title = "Average city miles per gallon", title = "City fuel economy by manufacturer", highlight = c("honda", "volkswagen"), value_format = ".1f" ) # Count rows, without aggregating first bar_chart(mpg, x = "class", sort = "descending", title = "Cars per class") # Grouped bars from raw data; switch to stacked or 100% from the chart bar_chart( data = mpg, x = "class", group = "drv", sort = "descending", title = "Cars per class and drive train", fill = c("4" = "#4269d0", "f" = "#efb118", "r" = "#ff725c") ) # Stacked, with a reference line sales <- data.frame( quarter = rep(c("Q1", "Q2", "Q3", "Q4"), each = 3), region = rep(c("North", "South", "West"), 4), revenue = c(120, 95, 60, 135, 90, 72, 150, 110, 80, 170, 105, 96) ) bar_chart( sales, x = "quarter", y = "revenue", group = "region", position = "stacked", ref_lines = c(Target = 300), value_prefix = "$", value_suffix = "k", title = "Revenue by quarter" )library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for data wrangling mpg %>% group_by(manufacturer) %>% summarise(mean_cty = mean(cty)) %>% bar_chart( x = "manufacturer", y = "mean_cty", sort = "descending", y_title = "Average city miles per gallon", title = "City fuel economy by manufacturer", highlight = c("honda", "volkswagen"), value_format = ".1f" ) # Count rows, without aggregating first bar_chart(mpg, x = "class", sort = "descending", title = "Cars per class") # Grouped bars from raw data; switch to stacked or 100% from the chart bar_chart( data = mpg, x = "class", group = "drv", sort = "descending", title = "Cars per class and drive train", fill = c("4" = "#4269d0", "f" = "#efb118", "r" = "#ff725c") ) # Stacked, with a reference line sales <- data.frame( quarter = rep(c("Q1", "Q2", "Q3", "Q4"), each = 3), region = rep(c("North", "South", "West"), 4), revenue = c(120, 95, 60, 135, 90, 72, 150, 110, 80, 170, 105, 96) ) bar_chart( sales, x = "quarter", y = "revenue", group = "region", position = "stacked", ref_lines = c(Target = 300), value_prefix = "$", value_suffix = "k", title = "Revenue by quarter" )
Ranks items (countries, products, teams...) by a value and animates the ranking through time: the bars glide past each other when they overtake, new items slide up from below the cut and leaving ones sink and fade, the value labels count smoothly, the axis follows the leader and a big period label sits in the corner. A player at the bottom plays, pauses and scrubs the animation.
bar_chart_race( data, x, y, time, ease = "Linear", frame_dur = 0, transition_dur = 1000, color_category = NULL, sort = "descending", padding_width = 0.2, x_font_size = 10, y_font_size = 12, x_ticks = NULL, x_title = NULL, x_title_font_size = 12, y_title = NULL, y_title_font_size = 12, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", panel_col = NULL, x_grid_line_col = NULL, opacity = 1, time_label = TRUE, time_label_opts = list(size = NULL, prefix = "", suffix = "", xOffset = 0, yOffset = 0), width = NULL, height = NULL, top_n = 10, group = NULL, fill = NULL, highlight = NULL, labels = TRUE, name_position = c("left", "inside"), total = FALSE, rank_flash = TRUE, agg = c("sum", "mean", "max", "min", "last"), corner_radius = 3, controls = TRUE, autoplay = TRUE, loop = FALSE, start_frame = "first", time_format = NULL, subtitle = NULL, subtitle_font_size = 13, value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, axis_col = "#333333" )bar_chart_race( data, x, y, time, ease = "Linear", frame_dur = 0, transition_dur = 1000, color_category = NULL, sort = "descending", padding_width = 0.2, x_font_size = 10, y_font_size = 12, x_ticks = NULL, x_title = NULL, x_title_font_size = 12, y_title = NULL, y_title_font_size = 12, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", panel_col = NULL, x_grid_line_col = NULL, opacity = 1, time_label = TRUE, time_label_opts = list(size = NULL, prefix = "", suffix = "", xOffset = 0, yOffset = 0), width = NULL, height = NULL, top_n = 10, group = NULL, fill = NULL, highlight = NULL, labels = TRUE, name_position = c("left", "inside"), total = FALSE, rank_flash = TRUE, agg = c("sum", "mean", "max", "min", "last"), corner_radius = 3, controls = TRUE, autoplay = TRUE, loop = FALSE, start_frame = "first", time_format = NULL, subtitle = NULL, subtitle_font_size = 13, value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, axis_col = "#333333" )
data |
The data frame containing the variables to consider (one row per item and period). |
x |
The name of the numeric column giving the length of the bars. |
y |
The name of the column giving the items (one bar per value). |
time |
The name of the column giving the periods: numeric (e.g.
years), |
ease |
The easing used within each period, a d3-ease name such as
|
frame_dur |
The time, in milliseconds, the race pauses on each period
before moving to the next one. Defaults to 0 (no pause). Each period
lasts |
transition_dur |
The time, in milliseconds, spent moving from one period to the next. Defaults to 1000. |
color_category |
Optional. The name of a D3 categorical colour scheme
(e.g. |
sort |
How the bars are ranked: |
padding_width |
The space between bars, as a share of the row height, from 0 to 0.99. Defaults to 0.2. |
x_font_size |
The font size of the value axis labels. Defaults to 10. |
y_font_size |
The font size of the item names (shrunk when the bars are thin). Defaults to 12. |
x_ticks |
Optional. The approximate number of value axis ticks. |
x_title |
Optional. The title of the value axis, drawn above it. It is also used as the name of the value in the tooltip. |
x_title_font_size |
The font size of the value axis title. Defaults to 12. |
y_title |
Optional. The title of the item names, drawn above them. |
y_title_font_size |
The font size of the item axis title. Defaults to 12. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
stroke |
Optional. The stroke colour of the bars. |
stroke_width |
Optional. The stroke width of the bars (1 when only
|
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour of the SVG. Defaults to "white". |
panel_col |
Optional. The background colour of the panel behind the bars (none by default). |
x_grid_line_col |
The colour of the vertical grid lines. When |
opacity |
The opacity of the bars (from 0 to 1). Defaults to 1. |
time_label |
Logical. Show the big period label in the bottom right
corner. Defaults to |
time_label_opts |
A list of options for the period label: |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
top_n |
The number of bars shown. Defaults to 10 (or the number of items, when there are fewer). |
group |
Optional. The name of a column grouping the items (e.g. the continent of each country). The bars are coloured by group, with a clickable legend. |
fill |
Optional. The colours of the bars: a single colour, an unnamed
vector (recycled over the items, or the groups with |
highlight |
Optional. A character vector of items followed from the start (the other bars are dimmed, see Interactions). |
labels |
Logical. Show the value at the end of each bar, counting
smoothly between periods. Defaults to |
name_position |
Where the item names go: |
total |
Show the total of all the items under the period label, and
the share of the total in the tooltip: |
rank_flash |
Logical. Flash a small arrow next to a bar that overtakes
another one. Defaults to |
agg |
How rows with the same item and period are combined:
|
corner_radius |
The radius of the rounded bar ends, in pixels. Defaults to 3; use 0 for square bars. |
controls |
Logical. Show the player (play / pause, timeline, speed,
loop) and the ranking length buttons. Defaults to |
autoplay |
Logical. Start playing when the chart scrolls into view.
Defaults to |
loop |
Logical. Start again at the end. Defaults to |
start_frame |
The period shown first: |
time_format |
Optional. A d3-time-format string for date periods, e.g.
|
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
tooltip |
Logical. Show a tooltip on hover. Defaults to |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
The data is long: one row per item and period, with the item names in
y, the values in x and the periods in time (numbers
such as years, dates, or a factor or character column whose levels give
the order). Gaps inside an item are interpolated; items missing before
their first or after their last period enter and leave the race.
An animated, interactive SVG bar chart race (an r2d3 htmlwidget).
The player at the bottom plays and pauses the race (also with the space bar), the timeline can be dragged or clicked, the arrow keys step one period, Home and End jump to the start and the end. The speed button cycles from 0.5x to 4x, the loop button repeats the race.
Hover a bar to see its value, its rank, its change over the last
period and (with total) its share of the total. The tooltip keeps
updating while the race plays.
Click a bar to follow it: it stays highlighted, the others are
dimmed, and when it falls out of the top top_n it is still shown
under the cut with its rank. Click it again, or press Escape, to stop
following. highlight follows items from the start.
With group, click a legend entry to hide or show a group (the
ranks are recomputed without it), double-click it to isolate it, hover
it to highlight its bars.
When there are more items than top_n, the buttons at the top
right switch between the top top_n and a longer ranking.
A small green arrow flashes next to a bar that overtakes another
(rank_flash).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a bar sets input$id_clicked to a list with the
item, its group, value, rank, period and
whether it is now followed; input$id_frame gives the period
shown (index and label). The current time, the speed, the
followed items, the hidden groups and the ranking length are kept when the
chart is re-rendered.
library(gapminder) library(dplyr) # let's select a set of countries only gapminder <- gapminder %>% filter( country %in% c("Algeria", "Mexico", "Iceland", "Greece", "Finland") ) bar_chart_race( data = gapminder, x = "lifeExp", y = "country", time = "year", y_title = "Country", x_title = "Life expectancy", title = "Bar chart race of countries life expectancy" ) # Every country, the top 10 coloured by continent, following France bar_chart_race( data = gapminder::gapminder, x = "pop", y = "country", time = "year", group = "continent", highlight = "France", total = "World", title = "The most populous countries", subtitle = "Population, 1952 to 2007" ) # Monthly dates, names inside the bars set.seed(1) months <- seq(as.Date("2023-01-01"), by = "month", length.out = 12) sales <- data.frame( brand = rep(c("Alpha", "Bravo", "Comet", "Delta", "Echo", "Fusion"), 12), month = rep(months, each = 6), units = round(runif(72, 20, 80)) ) sales$units <- ave(sales$units, sales$brand, FUN = cumsum) bar_chart_race( sales, x = "units", y = "brand", time = "month", name_position = "inside", ease = "CubicInOut", value_suffix = " units", title = "Units sold, year to date" )library(gapminder) library(dplyr) # let's select a set of countries only gapminder <- gapminder %>% filter( country %in% c("Algeria", "Mexico", "Iceland", "Greece", "Finland") ) bar_chart_race( data = gapminder, x = "lifeExp", y = "country", time = "year", y_title = "Country", x_title = "Life expectancy", title = "Bar chart race of countries life expectancy" ) # Every country, the top 10 coloured by continent, following France bar_chart_race( data = gapminder::gapminder, x = "pop", y = "country", time = "year", group = "continent", highlight = "France", total = "World", title = "The most populous countries", subtitle = "Population, 1952 to 2007" ) # Monthly dates, names inside the bars set.seed(1) months <- seq(as.Date("2023-01-01"), by = "month", length.out = 12) sales <- data.frame( brand = rep(c("Alpha", "Bravo", "Comet", "Delta", "Echo", "Fusion"), 12), month = rep(months, each = 6), units = round(runif(72, 20, 80)) ) sales$units <- ave(sales$units, sales$brand, FUN = cumsum) bar_chart_race( sales, x = "units", y = "brand", time = "month", name_position = "inside", ease = "CubicInOut", value_suffix = " units", title = "Units sold, year to date" )
A beeswarm plot displays individual data points along a numeric axis, spreading them out so they do not overlap (like a swarm of bees). It is a transparent alternative to box plots or violin plots because every observation is visible. When a grouping variable is supplied, one swarm is drawn per group along the opposite axis.
The layout is computed with a D3 force simulation that pulls each point toward its true value on the x-axis while resolving collisions so no two circles overlap.
The plot is interactive: hovering a point highlights it while dimming the
rest of the swarm, and (when tooltip columns are supplied) shows a
tooltip with those columns' values. When a group is supplied,
hovering a group label focuses that swarm and clicking a label toggles it
on or off. An optional mean/median reference line can be drawn per swarm.
The interactive behaviors are controlled by tooltip, hover,
animate, and stat.
beeswarm_plot( data, x, group = NULL, tooltip = NULL, hover = TRUE, animate = TRUE, stat = c("none", "mean", "median"), stat_color = "#d62728", col = "steelblue", color_palette = "Tableau10", radius = 4, opacity = 0.75, stroke = "white", stroke_width = 0.5, x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )beeswarm_plot( data, x, group = NULL, tooltip = NULL, hover = TRUE, animate = TRUE, stat = c("none", "mean", "median"), stat_color = "#d62728", col = "steelblue", color_palette = "Tableau10", radius = 4, opacity = 0.75, stroke = "white", stroke_width = 0.5, x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
x |
The name of the numeric column whose distribution is displayed. |
group |
Optional. The name of a categorical column used to split
the data into separate swarms. Defaults to |
tooltip |
Optional. A column name, or a vector of column names, whose
values are shown in a tooltip when a point is hovered. Each column appears
on its own line as |
hover |
Logical. When |
animate |
Logical. When |
stat |
Character. Draws a reference line per swarm at the
|
stat_color |
Color of the mean/median reference line and its label.
Defaults to |
col |
Fill color of the points when no |
color_palette |
D3 categorical color scheme used when |
radius |
Radius of each point in pixels. Defaults to |
opacity |
Fill opacity of the points (0 to 1). Defaults to |
stroke |
Stroke color of the points. Defaults to |
stroke_width |
Stroke width in pixels. Defaults to |
x_title |
Optional. Title of the x-axis. |
x_title_font_size |
Font size of the x-axis title. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
x_font_size |
Font size of the x-axis tick labels. Defaults to |
y_font_size |
Font size of the y-axis group labels. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of axis lines, ticks, and labels. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG beeswarm plot.
library(ggplot2) # for the mpg dataset # Single swarm — distribution of highway fuel economy beeswarm_plot( data = mpg, x = "hwy", col = "steelblue", x_title = "Highway miles per gallon", title = "Distribution of hwy" ) # Grouped swarm — hwy by vehicle class beeswarm_plot( data = mpg, x = "hwy", group = "class", x_title = "Highway miles per gallon", title = "Highway fuel economy by vehicle class" ) # Grouped swarm on the iris dataset beeswarm_plot( data = iris, x = "Sepal.Length", group = "Species", color_palette = "Set2", radius = 5, x_title = "Sepal length (cm)", title = "Sepal length by species" ) # Interactive extras: median line per swarm and a tooltip label column beeswarm_plot( data = mpg, x = "hwy", group = "class", tooltip = "model", stat = "median", x_title = "Highway miles per gallon", title = "Highway fuel economy by vehicle class" )library(ggplot2) # for the mpg dataset # Single swarm — distribution of highway fuel economy beeswarm_plot( data = mpg, x = "hwy", col = "steelblue", x_title = "Highway miles per gallon", title = "Distribution of hwy" ) # Grouped swarm — hwy by vehicle class beeswarm_plot( data = mpg, x = "hwy", group = "class", x_title = "Highway miles per gallon", title = "Highway fuel economy by vehicle class" ) # Grouped swarm on the iris dataset beeswarm_plot( data = iris, x = "Sepal.Length", group = "Species", color_palette = "Set2", radius = 5, x_title = "Sepal length (cm)", title = "Sepal length by species" ) # Interactive extras: median line per swarm and a tooltip label column beeswarm_plot( data = mpg, x = "hwy", group = "class", tooltip = "model", stat = "median", x_title = "Highway miles per gallon", title = "Highway fuel economy by vehicle class" )
Draws one box and whiskers per group: the box spans the first to the third
quartile, the thick line is the median, the whiskers reach the most extreme
values within 1.5 times the interquartile range, and the points beyond them
are drawn as outliers. The quartiles are computed in R
(stats::quantile(), type 7), so they match boxplot() and
ggplot2::geom_boxplot().
box_plot( data, y, group = NULL, horizontal = FALSE, points = c("outliers", "all", "none"), notch = FALSE, mean = TRUE, sort = c("none", "median", "mean"), colors = NULL, box_width = 0.6, point_radius = 3, value_format = ",.2~f", x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 11, y_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", grid_col = "#ececec", width = NULL, height = NULL )box_plot( data, y, group = NULL, horizontal = FALSE, points = c("outliers", "all", "none"), notch = FALSE, mean = TRUE, sort = c("none", "median", "mean"), colors = NULL, box_width = 0.6, point_radius = 3, value_format = ",.2~f", x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 11, y_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", grid_col = "#ececec", width = NULL, height = NULL )
data |
A data frame. |
y |
The name of the numeric column to summarise. |
group |
Optional. The name of a column that splits the data into boxes. Factor levels give the order. |
horizontal |
Logical. Draw horizontal boxes. Defaults to FALSE. |
points |
Which points to draw: |
notch |
Logical. Draw notches around the median (roughly a 95 percent interval for it). Defaults to FALSE. |
mean |
Logical. Mark the mean with a diamond. Defaults to TRUE. |
sort |
How to order the boxes: |
colors |
Optional. Colours of the boxes: one colour, one per group, or a named vector matched to the groups. |
box_width |
The width of the boxes, as a share of the space of each group (between 0.1 and 1). Defaults to 0.6. |
point_radius |
The radius of the points in pixels. Defaults to 3. |
value_format |
A d3 format for the values in the tooltips. Defaults to ",.2~f". |
x_title, y_title
|
Optional. The titles of the axes. By default the
value axis is titled with |
axis_title_font_size |
The font size of the axis titles. Defaults to 12. |
x_font_size, y_font_size
|
The font sizes of the tick labels. Default to 11. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Grow the boxes when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text and the axes. Defaults to "#333333". |
grid_col |
The colour of the grid lines; |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a box to see its summary (count, quartiles, mean, whiskers and number
of outliers) while the other boxes fade, and hover a point to see its value.
The boxes grow from their median when the chart is drawn. Inside Shiny,
clicking a box sets input$<id>_clicked to a list with the
group and its summary.
box_plot(iris, y = "Sepal.Length", group = "Species", title = "Sepal length") box_plot( mtcars, y = "mpg", group = "cyl", points = "all", notch = TRUE, colors = c("#4269d0", "#efb118", "#ff725c"), y_title = "Miles per gallon", x_title = "Cylinders" ) box_plot( ToothGrowth, y = "len", group = "dose", horizontal = TRUE, sort = "median", title = "Tooth length by dose" )box_plot(iris, y = "Sepal.Length", group = "Species", title = "Sepal length") box_plot( mtcars, y = "mpg", group = "cyl", points = "all", notch = TRUE, colors = c("#4269d0", "#efb118", "#ff725c"), y_title = "Miles per gallon", x_title = "Cylinders" ) box_plot( ToothGrowth, y = "len", group = "dose", horizontal = TRUE, sort = "median", title = "Tooth length by dose" )
Draws one bubble per item (id) at its x and y values,
sized by size and coloured by group, and animates the bubbles
smoothly from one period (time) to the next, in the style of the
famous Gapminder chart by Hans Rosling. The axes are fixed over the whole
race so that every move means something, the current period is drawn as a
large faded watermark behind the bubbles, and items that appear or
disappear fade in and out. Periods can be numbers (years), dates or
characters / factors.
bubble_race( data, x, y, id, time, size = NULL, group = NULL, x_scale = c("linear", "log"), y_scale = c("linear", "log"), size_range = c(3, 40), fill = NULL, color_category = NULL, opacity = 0.85, highlight = NULL, trails = FALSE, labels = 5, legend = NULL, size_legend = TRUE, buttons = TRUE, x_title = NULL, y_title = NULL, size_title = NULL, agg = c("mean", "sum", "max", "min", "last"), fill_gaps = TRUE, frame_dur = 1000, ease = "Linear", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", grid_col = "#ebebeb", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )bubble_race( data, x, y, id, time, size = NULL, group = NULL, x_scale = c("linear", "log"), y_scale = c("linear", "log"), size_range = c(3, 40), fill = NULL, color_category = NULL, opacity = 0.85, highlight = NULL, trails = FALSE, labels = 5, legend = NULL, size_legend = TRUE, buttons = TRUE, x_title = NULL, y_title = NULL, size_title = NULL, agg = c("mean", "sum", "max", "min", "last"), fill_gaps = TRUE, frame_dur = 1000, ease = "Linear", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", grid_col = "#ebebeb", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )
data |
The data frame containing the variables to consider, in long format (one row per item and period). |
x |
The name of the numeric column drawn on the horizontal axis. |
y |
The name of the numeric column drawn on the vertical axis. |
id |
The name of the column identifying the items (one bubble per value). |
time |
The name of the column giving the period: numeric (e.g. years), Date, POSIXct, factor or character (sorted, or in the order of the factor levels). |
size |
Optional. The name of a numeric, non-negative column giving the
size of the bubbles (their area is proportional to it). Without it, every
bubble has the same radius (7 pixels, or |
group |
Optional. The name of a column grouping the items (e.g. a continent). It sets the colours and adds a clickable legend. |
x_scale, y_scale
|
The scales of the axes: |
size_range |
A numeric vector of length 2: the smallest and the largest
bubble radius in pixels (the largest is reduced on small charts).
Defaults to |
fill |
Optional. The colours of the bubbles. With |
color_category |
Optional. The name of a D3 categorical colour scheme
used instead of the built-in palette, e.g. |
opacity |
The opacity of the bubbles, from 0 to 1. Defaults to 0.85. |
highlight |
Optional. A character vector of items to follow from the start (their trails and labels are drawn, the others are dimmed). |
trails |
Logical. Draw the trail of every bubble (best with a few
items). It can be switched from the chart. Defaults to |
labels |
The number of bubbles labelled with their name: the largest
ones (by |
legend |
Logical. Show the group legend. When |
size_legend |
Logical. Show a legend of reference circles for
|
buttons |
Logical. Show the buttons at the top right (log scales,
trails, clear). Defaults to |
x_title, y_title
|
Optional. The titles of the axes. They default to the
names of |
size_title |
Optional. The title of the size legend and the name of
the size in the tooltip. Defaults to the name of |
agg |
How rows with the same item and period are combined:
|
fill_gaps |
Logical. Interpolate the values of an item between the
periods where it is known, so that it does not blink out in a gap.
Defaults to |
frame_dur |
The duration of one period, in milliseconds. Defaults to 1000. |
ease |
The easing used between two periods, the name of a D3 easing
function without the "ease" prefix: |
autoplay |
Logical. Start playing when the chart scrolls into view.
Defaults to |
loop |
Logical. Start again at the end. It can be switched from the
player. Defaults to |
controls |
Logical. Show the player (play / pause, timeline, speed,
loop) at the bottom. Defaults to |
start_frame |
The first period shown: |
time_format |
Optional. A d3-time-format string used for Date and
POSIXct periods, e.g. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
font |
The font family of the texts. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour of the SVG. Defaults to "white". |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
grid_col |
The colour of the grid lines. Defaults to "#ebebeb"; use
|
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after the
values, e.g. |
tooltip |
Logical. Show a tooltip on hover. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An animated, interactive SVG bubble chart (an r2d3 htmlwidget).
The player at the bottom plays and pauses the race (also with the space bar), the timeline can be dragged or clicked, the arrow keys step one period, Home and End jump to the first and last period; speed and loop buttons sit on the right.
Hover a bubble to highlight it: guides are drawn to both axes with the values on the axes, and a tooltip lists its group, its values and their change over the last period. The tooltip stays on the bubble and keeps updating while the race plays.
Click a bubble to follow it: its trail (its path through every period so far, with a dot per period) is drawn, its label stays on, and the other bubbles are dimmed. Click it again to stop following it. Several bubbles can be followed. Hover a trail dot to see the values of that period, click it to jump to that period. Escape stops following every bubble.
The buttons at the top right switch the x and y axes between linear and log scales (when the values are all positive), show the trails of every bubble, and clear the followed bubbles.
Click a legend entry to hide or show a group, double-click it to isolate it. Hovering a legend entry highlights the group.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a bubble sets input$id_clicked to a list with the
id, group, x, y, size and
period of the bubble, input$id_followed gives the followed
items, and input$id_frame gives the current period (a list with
its index and label). The current period, the followed items,
the hidden groups, the scales and the trails mode are kept when the chart
is re-rendered.
library(gapminder) # needed for the gapminder data frame bubble_race( gapminder, x = "gdpPercap", y = "lifeExp", id = "country", time = "year", size = "pop", group = "continent", x_scale = "log", highlight = c("China", "India"), x_title = "GDP per capita", y_title = "Life expectancy", size_title = "Population", value_prefix = c(x = "$"), value_suffix = c(y = " years"), value_format = c(x = ",.0f", y = ".1f"), title = "Health and wealth of nations" ) # A few items with their trails library(dplyr) # needed for data wrangling gapminder %>% filter(country %in% c("China", "India", "Japan", "Brazil", "Nigeria")) %>% bubble_race( x = "gdpPercap", y = "lifeExp", id = "country", time = "year", size = "pop", x_scale = "log", trails = TRUE, labels = TRUE, title = "Five countries, 1952 to 2007" )library(gapminder) # needed for the gapminder data frame bubble_race( gapminder, x = "gdpPercap", y = "lifeExp", id = "country", time = "year", size = "pop", group = "continent", x_scale = "log", highlight = c("China", "India"), x_title = "GDP per capita", y_title = "Life expectancy", size_title = "Population", value_prefix = c(x = "$"), value_suffix = c(y = " years"), value_format = c(x = ",.0f", y = ".1f"), title = "Health and wealth of nations" ) # A few items with their trails library(dplyr) # needed for data wrangling gapminder %>% filter(country %in% c("China", "India", "Japan", "Brazil", "Nigeria")) %>% bubble_race( x = "gdpPercap", y = "lifeExp", id = "country", time = "year", size = "pop", x_scale = "log", trails = TRUE, labels = TRUE, title = "Five countries, 1952 to 2007" )
A bullet chart displays a single quantitative measure (the actual value) against qualitative range bands (e.g. poor / satisfactory / good) and an optional target marker. It was designed by Stephen Few as a compact, information-dense alternative to gauge charts.
bullet_chart( value, ranges, target = NULL, range_colors = NULL, title = "", subtitle = "", min = 0, value_color = "#1a1a2e", target_color = "#e63946", tick_count = 5, font_size = 12, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", width = NULL, height = NULL )bullet_chart( value, ranges, target = NULL, range_colors = NULL, title = "", subtitle = "", min = 0, value_color = "#1a1a2e", target_color = "#e63946", tick_count = 5, font_size = 12, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", width = NULL, height = NULL )
value |
Numeric. The actual value to display (the main bar). |
ranges |
Numeric vector of upper bounds for each qualitative band,
in ascending order (e.g. |
target |
Optional numeric. The target / goal value shown as a short
vertical marker. Defaults to |
range_colors |
Character vector of colors for each band, in the same
order as |
title |
Character. Label displayed to the left of the chart.
Defaults to |
subtitle |
Character. Smaller label displayed below |
min |
Numeric. The minimum value of the scale. Defaults to |
value_color |
The color of the actual-value bar. Defaults to
|
target_color |
The color of the target marker. Defaults to
|
tick_count |
Number of axis ticks. Defaults to |
font_size |
Base font size in pixels. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
The background color of the SVG. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG bullet chart.
# Sales revenue vs target bullet_chart( value = 270, target = 300, ranges = c(150, 225, 350), title = "Revenue", subtitle = "USD thousands" ) # Customer satisfaction score bullet_chart( value = 7.4, target = 8.0, ranges = c(4, 7, 10), title = "Satisfaction", subtitle = "out of 10", value_color = "steelblue" ) # Server response time (lower is better — ranges go poor → good left to right) bullet_chart( value = 320, target = 250, ranges = c(200, 500, 1000), range_colors = c("#f5f5f5", "#e0e0e0", "#c0c0c0"), title = "Response", subtitle = "ms", min = 0 )# Sales revenue vs target bullet_chart( value = 270, target = 300, ranges = c(150, 225, 350), title = "Revenue", subtitle = "USD thousands" ) # Customer satisfaction score bullet_chart( value = 7.4, target = 8.0, ranges = c(4, 7, 10), title = "Satisfaction", subtitle = "out of 10", value_color = "steelblue" ) # Server response time (lower is better — ranges go poor → good left to right) bullet_chart( value = 320, target = 250, ranges = c(200, 500, 1000), range_colors = c("#f5f5f5", "#e0e0e0", "#c0c0c0"), title = "Response", subtitle = "ms", min = 0 )
A bump chart shows how the rank of several entities changes across successive time periods. Each entity is drawn as a smooth line that moves up or down as it overtakes, or is overtaken by, the others, with a circle at every period showing its rank. Popularised by the Financial Times, The Economist and FiveThirtyEight (league tables, election polls, country rankings), it is the clearest way to tell a "who is ahead?" story when the order matters more than the exact values.
The data must be in long format: one row per entity and period. By
default the ranks are computed per period from the numeric y
column (rank 1 = highest value). Set ranked = TRUE if y
already contains the ranks.
bump_chart( data, x, y, group, ranked = FALSE, rank_order = "desc", colors = NULL, highlight = NULL, grey_col = "#d3d3d3", line_width = 3, circle_radius = 11, show_rank = TRUE, title = NULL, title_font_size = 16, x_font_size = 11, label_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )bump_chart( data, x, y, group, ranked = FALSE, rank_order = "desc", colors = NULL, highlight = NULL, grey_col = "#d3d3d3", line_width = 3, circle_radius = 11, show_rank = TRUE, title = NULL, title_font_size = 16, x_font_size = 11, label_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider, in long format (one row per group and period). |
x |
The name of the column holding the time period. Numeric and Date columns are ordered chronologically, factors follow their level order and character columns follow their order of appearance. |
y |
The name of the numeric column holding the value to rank (or the
rank itself when |
group |
The name of the column identifying each entity (one line per entity). Each group can appear at most once per period. |
ranked |
Whether |
rank_order |
How ranks are computed when |
colors |
Optional. A character vector of colors, recycled across the
groups in order of appearance, or a named vector mapping group names to
colors. Colors must be valid CSS colors (e.g. |
highlight |
Optional. A character vector of group names to highlight.
All other groups are drawn in |
grey_col |
Color used for groups that are not highlighted. Defaults to
|
line_width |
Width of the lines in pixels. Defaults to |
circle_radius |
Maximum radius of the circles in pixels. It is
reduced automatically when there are many groups or periods. Defaults to
|
show_rank |
Whether to print the rank number inside each circle.
Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
x_font_size |
Font size of the period labels on the x-axis. Defaults
to |
label_font_size |
Font size of the group labels drawn at both ends of
each line. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of the period labels, grid lines and title. Defaults
to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG bump chart.
# Points scored by five teams over four seasons league <- data.frame( season = rep(c("2023", "2024", "2025", "2026"), each = 5), team = rep(c("Lions", "Tigers", "Bears", "Wolves", "Eagles"), 4), points = c(80, 75, 60, 55, 50, 70, 82, 58, 66, 49, 65, 78, 72, 69, 52, 60, 74, 81, 70, 77) ) bump_chart( data = league, x = "season", y = "points", group = "team", title = "League ranking by season" ) # GDP per capita rank of the Asian "tiger" economies, highlighting two library(gapminder) countries <- c("Japan", "Singapore", "Hong Kong, China", "Taiwan", "Korea, Rep.", "Malaysia", "Thailand", "China") gdp <- gapminder[gapminder$country %in% countries & gapminder$year >= 1967, ] gdp$country <- as.character(gdp$country) bump_chart( data = gdp, x = "year", y = "gdpPercap", group = "country", highlight = c("Singapore", "Korea, Rep."), title = "GDP per capita rank, 1967-2007" )# Points scored by five teams over four seasons league <- data.frame( season = rep(c("2023", "2024", "2025", "2026"), each = 5), team = rep(c("Lions", "Tigers", "Bears", "Wolves", "Eagles"), 4), points = c(80, 75, 60, 55, 50, 70, 82, 58, 66, 49, 65, 78, 72, 69, 52, 60, 74, 81, 70, 77) ) bump_chart( data = league, x = "season", y = "points", group = "team", title = "League ranking by season" ) # GDP per capita rank of the Asian "tiger" economies, highlighting two library(gapminder) countries <- c("Japan", "Singapore", "Hong Kong, China", "Taiwan", "Korea, Rep.", "Malaysia", "Thailand", "China") gdp <- gapminder[gapminder$country %in% countries & gapminder$year >= 1967, ] gdp$country <- as.character(gdp$country) bump_chart( data = gdp, x = "year", y = "gdpPercap", group = "country", highlight = c("Singapore", "Korea, Rep."), title = "GDP per capita rank, 1967-2007" )
A calendar heatmap lays out one rounded square per day on a grid where each column is a week and each row is a day of the week, so a whole year fits in a single compact band. Each square is colored by the value recorded on that day using a sequential palette, which makes weekly rhythms, seasonal patterns, streaks and gaps easy to spot. The layout was popularised by GitHub's contribution graph and is the signature chart of the Frappe Charts library.
Month labels are drawn above the grid, weekday labels on its left, and a
"Less ... More" legend underneath. When the data span several years, one
panel is stacked per year. Days without data (and, when all values are
non-negative, days with a value of zero) are drawn in empty_col.
Hovering over a day shows a tooltip with its value and date, and hovering
over a legend square highlights the days that fall in that color bucket.
calendar_heatmap( data, date, value = NULL, aggregate = c("sum", "mean", "max", "min", "count"), week_start = c("sunday", "monday"), colors = c("#c0ddf9", "#73b3f3", "#3886e1", "#17459e"), empty_col = "#ebedf0", cell_radius = 2, cell_gap = 3, value_label = NULL, value_format = ",.2~f", date_format = "%a %b %-d, %Y", show_year_label = TRUE, show_month_labels = TRUE, show_weekday_labels = TRUE, label_font_size = 10, legend = TRUE, legend_labels = c("Less", "More"), hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#555555", width = NULL, height = NULL )calendar_heatmap( data, date, value = NULL, aggregate = c("sum", "mean", "max", "min", "count"), week_start = c("sunday", "monday"), colors = c("#c0ddf9", "#73b3f3", "#3886e1", "#17459e"), empty_col = "#ebedf0", cell_radius = 2, cell_gap = 3, value_label = NULL, value_format = ",.2~f", date_format = "%a %b %-d, %Y", show_year_label = TRUE, show_month_labels = TRUE, show_weekday_labels = TRUE, label_font_size = 10, legend = TRUE, legend_labels = c("Less", "More"), hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#555555", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
date |
The name of the column holding the dates. It can be of class
|
value |
Optional. The name of the numeric column holding the value of
each day. When |
aggregate |
How to combine several rows that share the same date. One
of |
week_start |
The first day of the week, i.e. the top row of the grid.
Either |
colors |
A vector of colors, from low to high, used to fill days that
have a value. Values are split into |
empty_col |
Fill color of days without data (or with a value of zero
when all values are non-negative). Defaults to |
cell_radius |
Corner radius of the day squares in pixels. Defaults to
|
cell_gap |
Gap between day squares in pixels. Defaults to |
value_label |
Optional. The unit shown after the value in the tooltip
and year totals (e.g. |
value_format |
A d3-format specifier used to display values (e.g.
|
date_format |
A d3-time-format specifier used to display dates in the
tooltip. Defaults to |
show_year_label |
Whether to print the year and its total above each
panel. Defaults to |
show_month_labels |
Whether to print month labels above the grid.
Defaults to |
show_weekday_labels |
Whether to print weekday labels (Mon, Wed, Fri) on
the left of the grid. Defaults to |
label_font_size |
Font size of the month, weekday, year and legend
labels. Defaults to |
legend |
Whether to display the "Less ... More" legend. Defaults to
|
legend_labels |
A character vector of length 2 giving the text drawn
on each side of the legend. Defaults to |
hover |
Whether to highlight the hovered day and show a tooltip.
Defaults to |
animate |
Whether the day squares fade in with a staggered animation
on first render. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of the title and of the month, weekday, year and
legend labels. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. Defaults to a height that fits the number of years displayed. |
An SVG calendar heatmap.
# One year of simulated daily activity, busier on weekdays set.seed(2026) days <- seq(as.Date("2026-01-01"), as.Date("2026-12-31"), by = "day") weekday <- !(format(days, "%u") %in% c("6", "7")) activity <- data.frame( day = days, commits = rpois(length(days), lambda = ifelse(weekday, 6, 1.5)) * rbinom(length(days), 1, 0.8) ) calendar_heatmap( data = activity, date = "day", value = "commits", title = "Commits in 2026" ) # Several years stacked, weeks starting on Monday, GitHub-like greens set.seed(1) days <- seq(as.Date("2021-01-01"), as.Date("2023-12-31"), by = "day") season <- 10 + 8 * sin(2 * pi * as.numeric(format(days, "%j")) / 365) rainfall <- data.frame(day = days, rain = pmax(0, rnorm(length(days), season, 6))) calendar_heatmap( data = rainfall, date = "day", value = "rain", week_start = "monday", colors = c("#9be9a8", "#40c463", "#30a14e", "#216e39"), value_label = "mm of rain", value_format = ",.1f", title = "Daily rainfall, 2021-2023" ) # Event log: one row per event, counted per day set.seed(7) events <- data.frame( when = as.Date("2025-01-01") + sample(0:364, 900, replace = TRUE) ) calendar_heatmap( data = events, date = "when", value_label = "orders", colors = c("#fde0c5", "#facba6", "#f59e72", "#e8603c", "#c0392b"), empty_col = "#f2f2f2", cell_radius = 3, title = "Orders per day" )# One year of simulated daily activity, busier on weekdays set.seed(2026) days <- seq(as.Date("2026-01-01"), as.Date("2026-12-31"), by = "day") weekday <- !(format(days, "%u") %in% c("6", "7")) activity <- data.frame( day = days, commits = rpois(length(days), lambda = ifelse(weekday, 6, 1.5)) * rbinom(length(days), 1, 0.8) ) calendar_heatmap( data = activity, date = "day", value = "commits", title = "Commits in 2026" ) # Several years stacked, weeks starting on Monday, GitHub-like greens set.seed(1) days <- seq(as.Date("2021-01-01"), as.Date("2023-12-31"), by = "day") season <- 10 + 8 * sin(2 * pi * as.numeric(format(days, "%j")) / 365) rainfall <- data.frame(day = days, rain = pmax(0, rnorm(length(days), season, 6))) calendar_heatmap( data = rainfall, date = "day", value = "rain", week_start = "monday", colors = c("#9be9a8", "#40c463", "#30a14e", "#216e39"), value_label = "mm of rain", value_format = ",.1f", title = "Daily rainfall, 2021-2023" ) # Event log: one row per event, counted per day set.seed(7) events <- data.frame( when = as.Date("2025-01-01") + sample(0:364, 900, replace = TRUE) ) calendar_heatmap( data = events, date = "when", value_label = "orders", colors = c("#fde0c5", "#facba6", "#f59e72", "#e8603c", "#c0392b"), empty_col = "#f2f2f2", cell_radius = 3, title = "Orders per day" )
Draws the open, high, low and close prices of each period as a candle: the body spans the open and the close (green when the price went up, red when it went down) and the wick spans the low and the high. Volumes can be shown as bars below the prices, and moving averages of the close as lines. The periods are drawn side by side, so days without trading leave no gap.
candlestick_chart( data, date, open, high, low, close, volume = NULL, moving_average = NULL, up_col = "#2e9d5b", down_col = "#e5484d", ma_colors = NULL, value_format = ",.2f", date_format = NULL, y_title = NULL, zoom = TRUE, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", grid_col = "#ececec", width = NULL, height = NULL )candlestick_chart( data, date, open, high, low, close, volume = NULL, moving_average = NULL, up_col = "#2e9d5b", down_col = "#e5484d", ma_colors = NULL, value_format = ",.2f", date_format = NULL, y_title = NULL, zoom = TRUE, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", grid_col = "#ececec", width = NULL, height = NULL )
data |
A data frame with one row per period. |
date |
The name of the column with the dates (Date, POSIXct or text). |
open, high, low, close
|
The names of the numeric columns with the prices. |
volume |
Optional. The name of a numeric column with the volumes. |
moving_average |
Optional. One or more window lengths (in periods) for
moving averages of the close, such as |
up_col, down_col
|
The colours of the rising and the falling candles. Default to "#2e9d5b" and "#e5484d". |
ma_colors |
Optional. The colours of the moving averages. |
value_format |
A d3 format for the prices. Defaults to ",.2f". |
date_format |
Optional. A d3 time format for the dates, such as "%d/%m/%Y". Defaults to "%b %-d, %Y" (with the time when the dates have one). |
y_title |
Optional. The title of the price axis. |
zoom |
Logical. Let the viewer zoom and pan in time. Defaults to TRUE. |
hover |
Logical. Show the crosshair and the prices. Defaults to TRUE. |
animate |
Logical. Let the candles appear when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text and the axes. Defaults to "#333333". |
grid_col |
The colour of the grid lines; |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Move the mouse over the chart: a crosshair follows it and the prices of the
period are written at the top. Scroll to zoom in time and drag to pan
(zoom); the price axis fits the visible candles, and a double-click
resets the view. The candles appear from left to right when the chart is
drawn. Inside Shiny, clicking a candle sets input$<id>_clicked to a
list with date, open, high, low, close
and volume.
# A simulated stock over 120 trading days set.seed(42) days <- seq(as.Date("2025-01-01"), by = "day", length.out = 170) days <- days[!format(days, "%u") %in% c("6", "7")][1:120] close <- 100 * cumprod(1 + rnorm(120, 0.001, 0.018)) open <- c(100, head(close, -1)) * (1 + rnorm(120, 0, 0.004)) stock <- data.frame( day = days, open = open, high = pmax(open, close) * (1 + abs(rnorm(120, 0, 0.008))), low = pmin(open, close) * (1 - abs(rnorm(120, 0, 0.008))), close = close, volume = round(rlnorm(120, 13, 0.4)) ) candlestick_chart(stock, date = "day", open = "open", high = "high", low = "low", close = "close", volume = "volume", moving_average = c(10, 30), value_format = "$,.2f", title = "A simulated stock") candlestick_chart(tail(stock, 40), date = "day", open = "open", high = "high", low = "low", close = "close", up_col = "#4269d0", down_col = "#ff725c")# A simulated stock over 120 trading days set.seed(42) days <- seq(as.Date("2025-01-01"), by = "day", length.out = 170) days <- days[!format(days, "%u") %in% c("6", "7")][1:120] close <- 100 * cumprod(1 + rnorm(120, 0.001, 0.018)) open <- c(100, head(close, -1)) * (1 + rnorm(120, 0, 0.004)) stock <- data.frame( day = days, open = open, high = pmax(open, close) * (1 + abs(rnorm(120, 0, 0.008))), low = pmin(open, close) * (1 - abs(rnorm(120, 0, 0.008))), close = close, volume = round(rlnorm(120, 13, 0.4)) ) candlestick_chart(stock, date = "day", open = "open", high = "high", low = "low", close = "close", volume = "volume", moving_average = c(10, 30), value_format = "$,.2f", title = "A simulated stock") candlestick_chart(tail(stock, 40), date = "day", open = "open", high = "high", low = "low", close = "close", up_col = "#4269d0", down_col = "#ff725c")
A chord diagram shows the flows (or connections) between a set of entities arranged around a circle. Each entity is drawn as an outer arc whose length is proportional to the total flow it is involved in, and each pair of entities is linked by a ribbon whose width at either end is proportional to the flow in that direction. Chord diagrams are a compact way to display migration, trade, transitions between states, or any other square matrix of flows.
The look and feel are inspired by the chord chart of the Nivo visualization library, reimplemented in plain D3. The chart is interactive: hovering an arc (or its label) keeps the ribbons connected to that entity and fades out all the others, while a tooltip lists the entity's totals and its largest flows. Hovering a ribbon isolates it and shows the flow in both directions. Clicking an arc pins its highlight; clicking it again, or clicking the background, releases it.
chord_diagram( data, from = "from", to = "to", value = "value", directed = TRUE, colors = NULL, color_palette = "Tableau10", ribbon_color = c("source", "target", "gradient"), sort_groups = c("none", "descending", "ascending"), pad_angle = 0.03, inner_radius_ratio = 0.92, arc_opacity = 1, ribbon_opacity = 0.6, fade_opacity = 0.1, stroke_width = 0.5, show_labels = TRUE, rotate_labels = FALSE, label_font_size = 11, label_offset = 10, value_format = ",~f", hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )chord_diagram( data, from = "from", to = "to", value = "value", directed = TRUE, colors = NULL, color_palette = "Tableau10", ribbon_color = c("source", "target", "gradient"), sort_groups = c("none", "descending", "ascending"), pad_angle = 0.03, inner_radius_ratio = 0.92, arc_opacity = 1, ribbon_opacity = 0.6, fade_opacity = 0.1, stroke_width = 0.5, show_labels = TRUE, rotate_labels = FALSE, label_font_size = 11, label_offset = 10, value_format = ",~f", hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )
data |
Either a data frame in edge-list format (one row per flow,
with the columns named by |
from |
The name of the column holding the origin of each flow. Only
used when |
to |
The name of the column holding the destination of each flow.
Only used when |
value |
The name of the numeric (non-negative) column holding the
size of each flow. Use |
directed |
Whether flows are directed. When |
colors |
Optional. A vector of colors for the entities, recycled if
needed. A named vector maps colors to entity names (unnamed entities fall
back to |
color_palette |
D3 categorical color scheme used when |
ribbon_color |
How ribbons are colored: |
sort_groups |
Order of the arcs around the circle: |
pad_angle |
Gap between adjacent arcs, in radians. Defaults to
|
inner_radius_ratio |
Inner radius of the arcs as a fraction of their
outer radius (between 0.5 and 0.99). Larger values give thinner arcs.
Defaults to |
arc_opacity |
Fill opacity of the arcs (0 to 1). Defaults to
|
ribbon_opacity |
Fill opacity of the ribbons (0 to 1). Defaults to
|
fade_opacity |
Opacity of the ribbons and arcs that are faded out
while another element is hovered (0 to 1). Defaults to |
stroke_width |
Width of the arc and ribbon borders in pixels (the
border uses a darker shade of the fill). Defaults to |
show_labels |
Whether to display the entity names outside the arcs.
Labels of arcs too small to hold them are hidden. Defaults to
|
rotate_labels |
Whether to orient the labels along the radius of the
circle (useful with many entities). When |
label_font_size |
Font size of the labels. Defaults to |
label_offset |
Distance in pixels between the arcs and their labels.
Defaults to |
value_format |
A d3-format specifier used to display values in the
tooltip (e.g. |
hover |
Whether hovering highlights arcs and ribbons and shows a
tooltip, and clicking an arc pins its highlight. Defaults to |
animate |
Whether the arcs sweep in and the ribbons fade in on first
render. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
text_col |
Color of the title and the labels. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG chord diagram.
# Edge list: hypothetical migration flows between regions (thousands) migration <- data.frame( from = c("Africa", "Africa", "Africa", "Asia", "Asia", "Asia", "Europe", "Europe", "Latin America", "Latin America", "North America", "Oceania", "Asia", "Europe"), to = c("Europe", "North America", "Asia", "Europe", "North America", "Oceania", "North America", "Asia", "North America", "Europe", "Europe", "Asia", "Africa", "Oceania"), value = c(420, 150, 90, 610, 520, 230, 180, 120, 870, 260, 95, 40, 60, 75) ) chord_diagram( data = migration, from = "from", to = "to", value = "value", value_format = ",.0f", title = "Migration flows between regions (thousands)" ) # Square matrix with dimnames: the classic hair-color transition data hair <- matrix( c(11975, 5871, 8916, 2868, 1951, 10048, 2060, 6171, 8010, 16145, 8090, 8045, 1013, 990, 940, 6907), nrow = 4, byrow = TRUE, dimnames = list(c("Black", "Blond", "Brown", "Red"), c("Black", "Blond", "Brown", "Red")) ) chord_diagram( data = hair, colors = c("#3b3b3b", "#f2c45a", "#8c5a3c", "#d0533a"), ribbon_color = "gradient", pad_angle = 0.05, value_format = ",.0f", title = "Hair color flows" ) # Undirected co-authorship links between departments, on a dark background coauthors <- data.frame( from = c("Biology", "Biology", "Biology", "Chemistry", "Chemistry", "Physics", "Physics", "Mathematics", "Computer Science", "Computer Science", "Medicine", "Medicine"), to = c("Chemistry", "Medicine", "Computer Science", "Physics", "Medicine", "Mathematics", "Computer Science", "Computer Science", "Medicine", "Biology", "Chemistry", "Physics"), value = c(34, 51, 18, 27, 22, 30, 25, 41, 16, 12, 9, 6) ) chord_diagram( data = coauthors, directed = FALSE, sort_groups = "descending", color_palette = "Set2", ribbon_opacity = 0.7, bg_col = "#1e1e2e", text_col = "#f0f0f0", title = "Joint publications between departments" )# Edge list: hypothetical migration flows between regions (thousands) migration <- data.frame( from = c("Africa", "Africa", "Africa", "Asia", "Asia", "Asia", "Europe", "Europe", "Latin America", "Latin America", "North America", "Oceania", "Asia", "Europe"), to = c("Europe", "North America", "Asia", "Europe", "North America", "Oceania", "North America", "Asia", "North America", "Europe", "Europe", "Asia", "Africa", "Oceania"), value = c(420, 150, 90, 610, 520, 230, 180, 120, 870, 260, 95, 40, 60, 75) ) chord_diagram( data = migration, from = "from", to = "to", value = "value", value_format = ",.0f", title = "Migration flows between regions (thousands)" ) # Square matrix with dimnames: the classic hair-color transition data hair <- matrix( c(11975, 5871, 8916, 2868, 1951, 10048, 2060, 6171, 8010, 16145, 8090, 8045, 1013, 990, 940, 6907), nrow = 4, byrow = TRUE, dimnames = list(c("Black", "Blond", "Brown", "Red"), c("Black", "Blond", "Brown", "Red")) ) chord_diagram( data = hair, colors = c("#3b3b3b", "#f2c45a", "#8c5a3c", "#d0533a"), ribbon_color = "gradient", pad_angle = 0.05, value_format = ",.0f", title = "Hair color flows" ) # Undirected co-authorship links between departments, on a dark background coauthors <- data.frame( from = c("Biology", "Biology", "Biology", "Chemistry", "Chemistry", "Physics", "Physics", "Mathematics", "Computer Science", "Computer Science", "Medicine", "Medicine"), to = c("Chemistry", "Medicine", "Computer Science", "Physics", "Medicine", "Mathematics", "Computer Science", "Computer Science", "Medicine", "Biology", "Chemistry", "Physics"), value = c(34, 51, 18, 27, 22, 30, 25, 41, 16, 12, 9, 6) ) chord_diagram( data = coauthors, directed = FALSE, sort_groups = "descending", color_palette = "Set2", ribbon_opacity = 0.7, bg_col = "#1e1e2e", text_col = "#f0f0f0", title = "Joint publications between departments" )
Draws a hierarchy as nested circles: every item is a circle whose area is proportional to its value, packed inside the circle of its group, itself packed inside the circle of its parent group, and so on. It shows the same part-to-whole structure as a treemap, with the groups easier to tell apart.
circle_packing( data, label, value = NULL, group = NULL, colors = NULL, padding = 3, show_labels = TRUE, value_format = ",.0f", label_font_size = 11, zoom = TRUE, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )circle_packing( data, label, value = NULL, group = NULL, colors = NULL, padding = 3, show_labels = TRUE, value_format = ",.0f", label_font_size = 11, zoom = TRUE, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
A data frame with one row per item. |
label |
The name of the column with the item names. |
value |
Optional. The name of a numeric column with the sizes. When
|
group |
Optional. The names of one or more columns giving the groups,
from the outermost to the innermost, such as |
colors |
Optional. Colours of the outermost groups: one per group or a named vector matched to the groups. |
padding |
The space between circles in pixels. Defaults to 3. |
show_labels |
Logical. Write the names of the circles that are large enough. Defaults to TRUE. |
value_format |
A d3 format for the values. Defaults to ",.0f". |
label_font_size |
The largest font size of the labels. Defaults to 11. |
zoom |
Logical. Click a group to zoom into it. Defaults to TRUE. |
legend |
Logical. Show a legend of the outermost groups. Defaults to TRUE. |
legend_font_size |
The font size of the legend. Defaults to 11. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Grow the circles when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text. Defaults to "#333333". |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a circle to see its value and its share of its group. Click a group
to zoom into it and click the background (or the zoomed group) to zoom
back out (zoom). The circles grow level by level when the chart is
drawn. Inside Shiny, clicking an item sets input$<id>_clicked to a
list with label, value and path (its groups).
# World population in 2007, by continent and country pop <- subset(gapminder::gapminder, year == 2007) circle_packing(pop, label = "country", value = "pop", group = "continent", title = "World population, 2007") # Car models, grouped by manufacturer, sized by the number of versions circle_packing(ggplot2::mpg, label = "model", group = "manufacturer", legend = FALSE) # Two levels of groups sales <- data.frame( region = rep(c("North", "South"), each = 6), category = rep(rep(c("Furniture", "Office", "Tech"), each = 2), 2), product = c("Chairs", "Tables", "Paper", "Pens", "Phones", "Laptops", "Chairs", "Tables", "Paper", "Pens", "Phones", "Laptops"), revenue = c(120, 90, 40, 25, 210, 260, 80, 110, 55, 30, 160, 190) ) circle_packing(sales, label = "product", value = "revenue", group = c("region", "category"), value_format = "$,.0f")# World population in 2007, by continent and country pop <- subset(gapminder::gapminder, year == 2007) circle_packing(pop, label = "country", value = "pop", group = "continent", title = "World population, 2007") # Car models, grouped by manufacturer, sized by the number of versions circle_packing(ggplot2::mpg, label = "model", group = "manufacturer", legend = FALSE) # Two levels of groups sales <- data.frame( region = rep(c("North", "South"), each = 6), category = rep(rep(c("Furniture", "Office", "Tech"), each = 2), 2), product = c("Chairs", "Tables", "Paper", "Pens", "Phones", "Laptops", "Chairs", "Tables", "Paper", "Pens", "Phones", "Laptops"), revenue = c(120, 90, 40, 25, 210, 260, 80, 110, 55, 30, 160, 190) ) circle_packing(sales, label = "product", value = "revenue", group = c("region", "category"), value_format = "$,.0f")
Draws a smooth estimate of the distribution of a numeric variable, one
curve per group, overlapping or stacked. The densities are computed in R
with stats::density(), so they match plot(density(x)) and
ggplot2::geom_density().
density_plot( data, x, group = NULL, bandwidth = "nrd0", adjust = 1, position = c("identity", "stack", "fill"), stat = c("none", "mean", "median"), rug = NULL, colors = NULL, fill_opacity = 0.35, line_width = 2, value_format = ",.2~f", x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 11, y_font_size = 11, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", grid_col = "#ececec", width = NULL, height = NULL )density_plot( data, x, group = NULL, bandwidth = "nrd0", adjust = 1, position = c("identity", "stack", "fill"), stat = c("none", "mean", "median"), rug = NULL, colors = NULL, fill_opacity = 0.35, line_width = 2, value_format = ",.2~f", x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 11, y_font_size = 11, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", grid_col = "#ececec", width = NULL, height = NULL )
data |
A data frame. |
x |
The name of the numeric column. |
group |
Optional. The name of a column that splits the data into curves. Factor levels give the order. |
bandwidth |
Optional. The smoothing bandwidth, a number or the name of
a rule understood by |
adjust |
A multiplier of the bandwidth: values above 1 give smoother curves. Defaults to 1. |
position |
|
stat |
Optional reference lines per curve: |
rug |
Logical. Draw the observations as small ticks along the axis. Defaults to TRUE when there are at most 1000 of them. |
colors |
Optional. Colours of the curves: one per group, or a named vector matched to the groups. |
fill_opacity |
The opacity of the areas. Defaults to 0.35. |
line_width |
The width of the curves. Defaults to 2. |
value_format |
A d3 format for the x values in the tooltip. Defaults to ",.2~f". |
x_title, y_title
|
Optional. The titles of the axes. The x axis is
titled with |
axis_title_font_size |
The font size of the axis titles. Defaults to 12. |
x_font_size, y_font_size
|
The font sizes of the tick labels. Default to 11. |
legend |
Logical. Show a legend when there are groups. Defaults to TRUE. |
legend_font_size |
The font size of the legend. Defaults to 11. |
hover |
Logical. Show the guide and the tooltip. Defaults to TRUE. |
animate |
Logical. Let the curves rise when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text and the axes. Defaults to "#333333". |
grid_col |
The colour of the grid lines; |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Move the mouse over the chart: a vertical guide follows it and the tooltip
gives the density of every group at that value. Click a group in the legend
to hide or show it. The curves rise from the axis when the chart is drawn.
Inside Shiny, clicking the chart sets input$<id>_clicked to a list
with the x value and the densities.
density_plot(faithful, x = "eruptions", title = "Old Faithful eruptions", x_title = "Duration (minutes)") density_plot(iris, x = "Petal.Length", group = "Species", stat = "median") density_plot( ggplot2::diamonds, x = "price", group = "cut", position = "fill", rug = FALSE, title = "Share of each cut along the price range" )density_plot(faithful, x = "eruptions", title = "Old Faithful eruptions", x_title = "Duration (minutes)") density_plot(iris, x = "Petal.Length", group = "Species", stat = "median") density_plot( ggplot2::diamonds, x = "price", group = "cut", position = "fill", rug = FALSE, title = "Share of each cut along the price range" )
Shows how a total is shared between items (browsers, energy sources, continents...) and how the shares change through time. A donut (or a pie) whose slices grow, shrink and smoothly slide past each other when the ranking changes is paired with a live league table: its rows slide to their new position and show the rank, a share bar, the share, the value and a green or red arrow when the item gained or lost places since the previous period. The centre of the donut shows the period and a total that counts smoothly. A player at the bottom plays, pauses and scrubs the animation.
donut_race( data, label, value, time, inner_radius = 0.6, sort = c("value", "fixed"), max_slices = NULL, other_label = "Other", table = TRUE, table_rows = NULL, labels = TRUE, center_label = "Total", fill = NULL, color_category = NULL, highlight = NULL, agg = c("sum", "mean", "max", "min", "last"), fill_gaps = TRUE, frame_dur = 900, ease = "CubicInOut", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )donut_race( data, label, value, time, inner_radius = 0.6, sort = c("value", "fixed"), max_slices = NULL, other_label = "Other", table = TRUE, table_rows = NULL, labels = TRUE, center_label = "Total", fill = NULL, color_category = NULL, highlight = NULL, agg = c("sum", "mean", "max", "min", "last"), fill_gaps = TRUE, frame_dur = 900, ease = "CubicInOut", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )
data |
The data frame containing the variables to consider (one row per item and period). |
label |
The name of the column giving the items (one slice per value). |
value |
The name of the numeric column giving the size of the slices. Negative, zero and missing values are left out (the item fades out). |
time |
The name of the column giving the periods: numeric (e.g.
years), |
inner_radius |
The inner radius of the donut, as a fraction of the outer radius (from 0 to 0.9). Defaults to 0.6; 0 draws a pie. |
sort |
The order of the slices, clockwise from the top:
|
max_slices |
Optional. The maximum number of slices: in each period,
the smallest items are grouped into an "Other" slice so that at most
|
other_label |
The label of the grouped slice. Defaults to "Other". |
table |
Logical. Show the league table next to the donut (or under
it when the chart is narrow). Defaults to |
table_rows |
Optional. The maximum number of rows of the table. Defaults to as many as fit. |
labels |
Logical. Write the share on the slices that are large enough.
Defaults to |
center_label |
The caption under the total in the centre of the donut.
Defaults to "Total"; |
fill |
Optional. The colours of the items: a single colour, one colour per item (in order of appearance, recycled), or a named vector mapping colours to items (the palette is used for the others). By default, the first colours of the palette go to the largest items. |
color_category |
Optional. The name of a D3 categorical colour scheme,
such as "Tableau10" or "Set2", used when |
highlight |
Optional. A character vector of items pinned from the start. |
agg |
How rows with the same item and period are combined:
|
fill_gaps |
Logical. Interpolate the missing values of an item between
two periods where it is known. Defaults to |
frame_dur |
The duration of one period of the animation, in milliseconds. Defaults to 900. |
ease |
The easing used inside each period, the name of a D3 easing function without the "ease" prefix, such as "Linear" or "CubicInOut" (default), see <https://github.com/d3/d3-ease>. |
autoplay |
Logical. Start playing when the chart scrolls into view.
Defaults to |
loop |
Logical. Start again at the end. Defaults to |
controls |
Logical. Show the player (play button, timeline, speed and
loop buttons). Defaults to |
start_frame |
Where the animation starts: |
time_format |
Optional. A D3 time format for date periods, such as
|
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 20. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
font |
The font family of the chart. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
axis_col |
The colour of the texts. Defaults to "#333333". |
value_format |
Optional. A D3 format string for the values, such as
|
value_prefix, value_suffix
|
Optional. Text added before and after the
values, such as |
tooltip |
Logical. Show a tooltip when hovering the slices and the
rows. Defaults to |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
The data is long: one row per item and period, with the item names in
label, the values in value and the periods in time
(numbers such as years, dates, or a factor or character column whose
levels give the order). Rows with the same item and period are combined
with agg. Gaps inside an item are interpolated; items missing before
their first or after their last period grow in from zero and fade out.
With max_slices, the smallest items of each period are grouped into
an "Other" slice: items flow into it and out of it smoothly when they cross
the cut, and the table still ranks every item.
An interactive, animated SVG donut race (an r2d3 htmlwidget).
The player at the bottom plays and pauses the race (also with the space bar), the timeline can be dragged or clicked, the arrow keys step one period, Home and End jump to the start and the end. The speed button cycles from 0.5x to 4x, the loop button repeats the race.
Hover a slice or a table row: both are highlighted (the slice pulls out, the row is emphasised, the centre shows the share of the item) and a tooltip gives the value, the share, the rank and the change since the previous period. The tooltip keeps updating while the race plays. Hovering the "Other" slice lists the items it contains.
Click a slice or a row to pin it (it stays pulled out and
highlighted in the table, the other slices are dimmed), click it again
to unpin it, or click the background to unpin every item.
highlight pins items from the start.
Alt-click (or shift-click) a row or a slice, or click the small cross at the end of a hovered row, to hide an item: the shares and the ranks are recomputed without it, and the slices close the gap smoothly. The "Show all" button at the top right brings the hidden items back.
The buttons at the top right switch the order of the slices between the ranking (largest first) and the fixed order of the data.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a slice or a row sets input$id_clicked to a list with the
label of the item, its value, share, rank, the
period and whether it is now pinned. input$id_hidden
gives the hidden items and input$id_frame the period shown
(index and label). The current time, the speed, the pinned
and hidden items and the slice order are kept when the chart is
re-rendered.
library(gapminder) # The world population by continent donut_race( gapminder, label = "continent", value = "pop", time = "year", title = "World population by continent" ) # The 7 most populous countries of each period, the others grouped donut_race( gapminder, label = "country", value = "pop", time = "year", max_slices = 8, inner_radius = 0.55, highlight = "India", title = "Who holds the world population?" ) # Character periods, a pie and a fixed order energy <- data.frame( source = rep(c("Coal", "Gas", "Nuclear", "Hydro", "Wind", "Solar"), 3), period = rep(c("2000s", "2010s", "2020s"), each = 6), twh = c(40, 20, 17, 16, 1, 0, 33, 23, 15, 16, 6, 2, 25, 24, 13, 15, 13, 10) ) donut_race( energy, label = "source", value = "twh", time = "period", inner_radius = 0, sort = "fixed", value_suffix = " %" )library(gapminder) # The world population by continent donut_race( gapminder, label = "continent", value = "pop", time = "year", title = "World population by continent" ) # The 7 most populous countries of each period, the others grouped donut_race( gapminder, label = "country", value = "pop", time = "year", max_slices = 8, inner_radius = 0.55, highlight = "India", title = "Who holds the world population?" ) # Character periods, a pie and a fixed order energy <- data.frame( source = rep(c("Coal", "Gas", "Nuclear", "Hydro", "Wind", "Solar"), 3), period = rep(c("2000s", "2010s", "2020s"), each = 6), twh = c(40, 20, 17, 16, 1, 0, 33, 23, 15, 16, 6, 2, 25, 24, 13, 15, 13, 10) ) donut_race( energy, label = "source", value = "twh", time = "period", inner_radius = 0, sort = "fixed", value_suffix = " %" )
A dumbbell chart (also called a connected dot plot) displays two values per category as dots connected by a horizontal line. It is ideal for showing the change or gap between two groups, time points, or conditions across multiple categories — a clean alternative to grouped bar charts favoured by outlets such as the New York Times and The Economist.
dumbbell_chart( data, x1, x2, y, x1_label = NULL, x2_label = NULL, col1 = "steelblue", col2 = "crimson", line_col = "#aaaaaa", line_width = 2, circle_radius = 6, sort = "none", x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, legend = TRUE, legend_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )dumbbell_chart( data, x1, x2, y, x1_label = NULL, x2_label = NULL, col1 = "steelblue", col2 = "crimson", line_col = "#aaaaaa", line_width = 2, circle_radius = 6, sort = "none", x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, legend = TRUE, legend_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
x1 |
The name of the column for the first value (left dot). |
x2 |
The name of the column for the second value (right dot). |
y |
The name of the categorical column used as row labels. |
x1_label |
Legend label for the first value. Defaults to the value of
|
x2_label |
Legend label for the second value. Defaults to the value of
|
col1 |
Color of the first dot. Defaults to |
col2 |
Color of the second dot. Defaults to |
line_col |
Color of the line connecting the two dots. Defaults to
|
line_width |
Width of the connecting line in pixels. Defaults to
|
circle_radius |
Radius of the dots in pixels. Defaults to |
sort |
Whether to sort the rows. One of |
x_title |
Optional. Title of the x-axis. |
x_title_font_size |
Font size of the x-axis title. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
x_font_size |
Font size of the x-axis tick labels. Defaults to |
y_font_size |
Font size of the y-axis category labels. Defaults to
|
legend |
Whether to display a legend. Defaults to |
legend_font_size |
Font size of the legend text. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of axis lines, ticks, and labels. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG dumbbell chart.
# Life expectancy change between 1952 and 2007 for selected countries life_exp <- data.frame( country = c("Brazil", "China", "Egypt", "India", "Japan", "Mexico", "Nigeria", "Turkey"), year_1952 = c(50.9, 44.0, 41.9, 37.4, 63.0, 50.8, 36.3, 43.6), year_2007 = c(72.4, 72.9, 71.3, 64.7, 82.6, 76.2, 46.9, 71.8) ) dumbbell_chart( data = life_exp, x1 = "year_1952", x2 = "year_2007", y = "country", x1_label = "1952", x2_label = "2007", title = "Life expectancy: 1952 vs 2007", x_title = "Life expectancy (years)", sort = "ascending" ) # Comparing city vs highway fuel economy by car class library(ggplot2) library(dplyr) mpg_summary <- summarise(group_by(mpg, class), city = mean(cty), highway = mean(hwy)) dumbbell_chart( data = mpg_summary, x1 = "city", x2 = "highway", y = "class", x1_label = "City", x2_label = "Highway", col1 = "steelblue", col2 = "darkorange", title = "City vs highway fuel economy by class", x_title = "Miles per gallon", sort = "ascending" )# Life expectancy change between 1952 and 2007 for selected countries life_exp <- data.frame( country = c("Brazil", "China", "Egypt", "India", "Japan", "Mexico", "Nigeria", "Turkey"), year_1952 = c(50.9, 44.0, 41.9, 37.4, 63.0, 50.8, 36.3, 43.6), year_2007 = c(72.4, 72.9, 71.3, 64.7, 82.6, 76.2, 46.9, 71.8) ) dumbbell_chart( data = life_exp, x1 = "year_1952", x2 = "year_2007", y = "country", x1_label = "1952", x2_label = "2007", title = "Life expectancy: 1952 vs 2007", x_title = "Life expectancy (years)", sort = "ascending" ) # Comparing city vs highway fuel economy by car class library(ggplot2) library(dplyr) mpg_summary <- summarise(group_by(mpg, class), city = mean(cty), highway = mean(hwy)) dumbbell_chart( data = mpg_summary, x1 = "city", x2 = "highway", y = "class", x1_label = "City", x2_label = "Highway", col1 = "steelblue", col2 = "darkorange", title = "City vs highway fuel economy by class", x_title = "Miles per gallon", sort = "ascending" )
Draws a flame whose height follows an intensity: the higher the
intensity, the taller the flame, the faster it flickers and the more sparks
it throws. The flame is made of three layers (outer, middle and core) with a
warm glow behind it, and can burn on its own, on a candle or on logs. Useful
to show the state of a critical number, such as the number of errors in a
process. When the chart scrolls into view, the flame ignites and grows to
its height while the value (with show_value = TRUE) counts up.
flame( intensity = 50, flame_gradient_colors = c("#fffbe6", "#ffc233", "#e8452c"), flame_outline = NULL, bg_col = "white", width = NULL, height = NULL, max_intensity = 100, base = c("none", "candle", "logs"), show_value = FALSE, value_suffix = "", title_text = NULL, title_color = NULL, title_font_size = 14, label_color = NULL, label_font_size = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", flicker = TRUE, sparks = TRUE, draggable = FALSE, animate = TRUE )flame( intensity = 50, flame_gradient_colors = c("#fffbe6", "#ffc233", "#e8452c"), flame_outline = NULL, bg_col = "white", width = NULL, height = NULL, max_intensity = 100, base = c("none", "candle", "logs"), show_value = FALSE, value_suffix = "", title_text = NULL, title_color = NULL, title_font_size = 14, label_color = NULL, label_font_size = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", flicker = TRUE, sparks = TRUE, draggable = FALSE, animate = TRUE )
intensity |
A non-negative number: the intensity of the flame. The
height of the flame grows linearly with it up to |
flame_gradient_colors |
A length-3 character vector of colours, from
the core of the flame outwards. Defaults to
|
flame_outline |
Optional. The colour of an outline drawn around the flame. By default the flame has no outline. |
bg_col |
The background colour. Defaults to "white". The flame glows more on dark backgrounds. |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
max_intensity |
The intensity at which the flame reaches its full height. Defaults to 100. Higher intensities do not make the flame taller. |
base |
What the flame burns on: "none" (the default), "candle" or "logs". |
show_value |
Logical. Write the intensity below the flame. Defaults to FALSE. |
value_suffix |
A text added after the value, such as " errors". Defaults to "". |
title_text |
Optional. A caption below the flame. |
title_color |
Optional. The colour of the caption. Defaults to
|
title_font_size |
The font size of the caption. Defaults to 14. |
label_color |
Optional. The colour of the value. Defaults to dark grey on light backgrounds and light grey on dark ones. |
label_font_size |
Optional. The font size of the value. By default it depends on the size of the chart. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
flicker |
Logical. Animate the flame. Defaults to TRUE. |
sparks |
Logical. Show sparks rising from the flame. Defaults to TRUE. |
draggable |
Logical. Let the viewer change the intensity by dragging or with the arrow keys. Defaults to FALSE. |
animate |
Logical. Ignite the flame when it first comes into view. Defaults to TRUE. |
An r2d3 htmlwidget.
Move the mouse near the flame: it leans away, as if you were blowing on it.
Click the flame: it flares up and throws a burst of sparks.
With draggable = TRUE, drag up or down on the flame to set
the intensity, or focus the chart (click it or press Tab) and use the
arrow keys.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking the flame sets input$id_clicked to a list with
intensity, and, with draggable = TRUE, setting the intensity
sets input$id_value to the new intensity. When the chart is
re-rendered with a new intensity, the flame grows or shrinks from the old
height to the new one.
flame(intensity = 20) flame( intensity = 80, flame_gradient_colors = c("#e0f7ff", "#5ac8fa", "#1d4ed8"), bg_col = "#111111", base = "logs" ) flame( intensity = 35, base = "candle", show_value = TRUE, value_suffix = " errors", title_text = "Failed jobs today" )flame(intensity = 20) flame( intensity = 80, flame_gradient_colors = c("#e0f7ff", "#5ac8fa", "#1d4ed8"), bg_col = "#111111", base = "logs" ) flame( intensity = 35, base = "candle", show_value = TRUE, value_suffix = " errors", title_text = "Failed jobs today" )
Draws a flower that blooms when it scrolls into view (the petals unfold one after the other) and then turns slowly. The petals have soft gradients, a second ring of petals sits behind them and the centre is covered with stamens laid out on a golden-angle spiral. Petals can be plucked: "loves me, loves me not".
flower( petal_count = 6, petal_length = NULL, petal_width = NULL, petal_color = "#ff8ab7", petal_stroke = NULL, center_radius = NULL, center_color = "#f6c445", center_stroke = "#e09a1a", center_text = NULL, center_text_size = 16, center_text_color = "#222", font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", rotation_speed = 0.5, width = NULL, height = NULL, petal_values = NULL, petal_labels = NULL, value_suffix = "", layers = 2, stamens = TRUE, pluck = TRUE, bloom = TRUE, title_text = NULL, title_color = NULL, title_font_size = 14 )flower( petal_count = 6, petal_length = NULL, petal_width = NULL, petal_color = "#ff8ab7", petal_stroke = NULL, center_radius = NULL, center_color = "#f6c445", center_stroke = "#e09a1a", center_text = NULL, center_text_size = 16, center_text_color = "#222", font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", rotation_speed = 0.5, width = NULL, height = NULL, petal_values = NULL, petal_labels = NULL, value_suffix = "", layers = 2, stamens = TRUE, pluck = TRUE, bloom = TRUE, title_text = NULL, title_color = NULL, title_font_size = 14 )
petal_count |
The number of petals. Defaults to 6. Ignored when
|
petal_length |
Optional. The length of the petals (the longest one
with |
petal_width |
Optional. The width of the petals in pixels. By default it depends on their length and number. |
petal_color |
The colour of the petals: one colour, or one per petal
(recycled). Defaults to "#ff8ab7", or to the ddplot palette with
|
petal_stroke |
Optional. The outline colour of the petals. By default a darker shade of each petal colour is used. |
center_radius |
Optional. The radius of the centre in pixels. By default it is a fifth of the petal length. |
center_color |
The colour of the centre. Defaults to "#f6c445". |
center_stroke |
The outline colour of the centre (and the colour of the stamens). Defaults to "#e09a1a". |
center_text |
Optional. A text written in the centre (e.g. a number). |
center_text_size |
The font size of the centre text. Defaults to 16. |
center_text_color |
The colour of the centre text. Defaults to "#222". |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
rotation_speed |
The speed of rotation, in degrees per 20
milliseconds (0 to stop it). Defaults to 0.5, or to 0 with
|
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
petal_values |
Optional. A numeric vector: one petal per value, with a length proportional to the value. |
petal_labels |
Optional. A character vector of labels for the petals
(with |
value_suffix |
A text added after the values in the tooltips, such as " pts". Defaults to "". |
layers |
The number of rings of petals: 1, or 2 (the default) for a
second, darker ring behind the first. Ignored with |
stamens |
Logical. Draw the stamens on the centre. Defaults to TRUE. |
pluck |
Logical. Let the viewer pluck the petals by clicking them. Defaults to TRUE. |
bloom |
Logical. Unfold the petals when the flower first comes into view. Defaults to TRUE. |
title_text |
Optional. A caption below the flower. |
title_color |
Optional. The colour of the caption. |
title_font_size |
The font size of the caption. Defaults to 14. |
With petal_values, the flower becomes a small chart: there is one
petal per value, its length is proportional to the value, the petals are
labelled with petal_labels and hovering a petal shows its value and
share of the total.
An r2d3 htmlwidget.
Hover the flower: it stops turning and the petal under the mouse
grows slightly (with petal_values, a tooltip shows its value and
share).
Click a petal to pluck it: it falls to the ground and the flower
says "loves me" or "loves me not". When the last petal is plucked, the
verdict is shown and the flower grows back. Click the centre to make
every petal grow back. With petal_values, clicking a petal
highlights it instead (click it again to clear).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a petal sets input$id_clicked to a list with petal
(its number, 0 for the centre) and, when plucking, plucked,
remaining and lovesMe; with petal_values, it has
petal, label and value (NULL when the
highlight is cleared). The angle of the flower is kept when the chart is
re-rendered, and the bloom is played only once.
flower( petal_count = 5, petal_color = "plum", rotation_speed = 1.5 ) flower(petal_count = 12, petal_color = "#efb118", center_color = "#5b3a29", center_stroke = "#3b2416", center_text = "12", center_text_color = "white") flower( petal_values = c(8, 6, 9, 4, 7), petal_labels = c("Speed", "Power", "Skill", "Luck", "Focus"), title_text = "Player profile" )flower( petal_count = 5, petal_color = "plum", rotation_speed = 1.5 ) flower(petal_count = 12, petal_color = "#efb118", center_color = "#5b3a29", center_stroke = "#3b2416", center_text = "12", center_text_color = "white") flower( petal_values = c(8, 6, 9, 4, 7), petal_labels = c("Speed", "Power", "Skill", "Luck", "Focus"), title_text = "Player profile" )
Draws the stages of a process (visits, sign-ups, purchases, ...) as centred bars whose width is proportional to their value, from the first stage at the top to the last at the bottom. The conversion from one stage to the next is written between the bars and the share of the first stage on the right.
funnel_chart( data, stage, value, colors = NULL, shape = c("funnel", "bars"), show_conversion = TRUE, show_percent = TRUE, value_format = ",.0f", label_font_size = 12, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )funnel_chart( data, stage, value, colors = NULL, shape = c("funnel", "bars"), show_conversion = TRUE, show_percent = TRUE, value_format = ",.0f", label_font_size = 12, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
A data frame with one row per stage, in order (or a factor giving the order). Rows of the same stage are added up. |
stage |
The name of the column with the stages. |
value |
The name of the numeric column with the values. |
colors |
Optional. One colour (the stages get lighter shades of it) or one colour per stage. Defaults to shades of blue. |
shape |
|
show_conversion |
Logical. Write the conversion from each stage to the next between the bars. Defaults to TRUE. |
show_percent |
Logical. Write the share of the first stage on the right. Defaults to TRUE. |
value_format |
A d3 format for the values. Defaults to ",.0f". |
label_font_size |
The font size of the labels. Defaults to 12. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Grow the bars when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text. Defaults to "#333333". |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a stage to see its value, its share of the first stage, the
conversion from the previous stage and how many were lost on the way. The
bars grow one after the other when the chart is drawn. Inside Shiny,
clicking a stage sets input$<id>_clicked to a list with
stage, value, percent_of_first and
conversion.
shop <- data.frame( step = c("Visited the site", "Viewed a product", "Added to cart", "Started checkout", "Paid"), users = c(12000, 7400, 2900, 1650, 1180) ) funnel_chart(shop, stage = "step", value = "users", title = "Online shop, last 30 days") hiring <- data.frame( stage = c("Applications", "Screened", "Interviewed", "Offer", "Hired"), people = c(420, 160, 48, 12, 9) ) funnel_chart(hiring, stage = "stage", value = "people", shape = "bars", colors = "#3ca951")shop <- data.frame( step = c("Visited the site", "Viewed a product", "Added to cart", "Started checkout", "Paid"), users = c(12000, 7400, 2900, 1650, 1180) ) funnel_chart(shop, stage = "step", value = "users", title = "Online shop, last 30 days") hiring <- data.frame( stage = c("Applications", "Screened", "Interviewed", "Offer", "Hired"), people = c(420, 160, 48, 12, 9) ) funnel_chart(hiring, stage = "stage", value = "people", shape = "bars", colors = "#3ca951")
Draws tasks as bars along a time axis, one row per task, from their start
to their end. Tasks can be coloured by group, show how far along they are
(progress), depend on other tasks (drawn as arrows) and be compared
with today's date. A task that starts and ends on the same date is drawn as
a milestone (a diamond).
gantt_chart( data, task, start, end, group = NULL, progress = NULL, depends_on = NULL, today = NULL, sort = c("none", "start", "group"), colors = NULL, bar_height = 0.6, date_format = NULL, label_font_size = 11, zoom = TRUE, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )gantt_chart( data, task, start, end, group = NULL, progress = NULL, depends_on = NULL, today = NULL, sort = c("none", "start", "group"), colors = NULL, bar_height = 0.6, date_format = NULL, label_font_size = 11, zoom = TRUE, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
A data frame with one row per task. |
task |
The name of the column with the task names. |
start, end
|
The names of the columns with the start and end dates (Date, POSIXct, or text such as "2025-03-14"). |
group |
Optional. The name of a column to colour the tasks by (a team, a phase, ...). |
progress |
Optional. The name of a numeric column with the share of each task that is done, between 0 and 1. |
depends_on |
Optional. The name of a column with, for each task, the name of the task(s) it depends on (several names separated by commas). |
today |
Optional. A date to mark with a vertical line, or |
sort |
How to order the tasks: |
colors |
Optional. Colours of the groups: one per group or a named vector matched to the groups. |
bar_height |
The height of the bars as a share of each row. Defaults to 0.6. |
date_format |
Optional. A d3 time format for the dates in the tooltip, such as "%d/%m/%Y". Defaults to "%b %-d, %Y" (with the time when the dates have one). |
label_font_size |
The font size of the task names. Defaults to 11. |
zoom |
Logical. Let the viewer zoom and pan in time. Defaults to TRUE. |
legend |
Logical. Show a legend of the groups. Defaults to TRUE. |
legend_font_size |
The font size of the legend. Defaults to 11. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Grow the bars when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text. Defaults to "#333333". |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a task to see its dates, duration and progress, and to highlight the
tasks it depends on and the ones that depend on it. Scroll to zoom in time
and drag to pan (zoom); double-click to reset. The bars grow from
their start when the chart is drawn. Inside Shiny, clicking a task sets
input$<id>_clicked to a list with task, start,
end and group.
plan <- data.frame( task = c("Kick-off", "Research", "Design", "Prototype", "User tests", "Build", "QA", "Launch"), start = as.Date(c("2025-01-06", "2025-01-07", "2025-01-27", "2025-02-17", "2025-03-10", "2025-03-03", "2025-04-14", "2025-05-05")), end = as.Date(c("2025-01-06", "2025-01-31", "2025-02-21", "2025-03-07", "2025-03-21", "2025-04-18", "2025-05-02", "2025-05-05")), team = c("All", "Design", "Design", "Engineering", "Design", "Engineering", "Engineering", "All"), done = c(1, 1, 1, 0.8, 0.4, 0.3, 0, 0), after = c(NA, "Kick-off", "Research", "Design", "Prototype", "Design", "Build", "QA, User tests") ) gantt_chart(plan, task = "task", start = "start", end = "end", group = "team", progress = "done", depends_on = "after", today = as.Date("2025-03-14"), title = "Product launch") # The reigns of the last six British monarchs reigns <- data.frame( monarch = c("Victoria", "Edward VII", "George V", "Edward VIII", "George VI", "Elizabeth II"), from = as.Date(c("1837-06-20", "1901-01-22", "1910-05-06", "1936-01-20", "1936-12-11", "1952-02-06")), to = as.Date(c("1901-01-22", "1910-05-06", "1936-01-20", "1936-12-11", "1952-02-06", "2022-09-08")) ) gantt_chart(reigns, task = "monarch", start = "from", end = "to", colors = "#a463f2", date_format = "%Y")plan <- data.frame( task = c("Kick-off", "Research", "Design", "Prototype", "User tests", "Build", "QA", "Launch"), start = as.Date(c("2025-01-06", "2025-01-07", "2025-01-27", "2025-02-17", "2025-03-10", "2025-03-03", "2025-04-14", "2025-05-05")), end = as.Date(c("2025-01-06", "2025-01-31", "2025-02-21", "2025-03-07", "2025-03-21", "2025-04-18", "2025-05-02", "2025-05-05")), team = c("All", "Design", "Design", "Engineering", "Design", "Engineering", "Engineering", "All"), done = c(1, 1, 1, 0.8, 0.4, 0.3, 0, 0), after = c(NA, "Kick-off", "Research", "Design", "Prototype", "Design", "Build", "QA, User tests") ) gantt_chart(plan, task = "task", start = "start", end = "end", group = "team", progress = "done", depends_on = "after", today = as.Date("2025-03-14"), title = "Product launch") # The reigns of the last six British monarchs reigns <- data.frame( monarch = c("Victoria", "Edward VII", "George V", "Edward VIII", "George VI", "Elizabeth II"), from = as.Date(c("1837-06-20", "1901-01-22", "1910-05-06", "1936-01-20", "1936-12-11", "1952-02-06")), to = as.Date(c("1901-01-22", "1910-05-06", "1936-01-20", "1936-12-11", "1952-02-06", "2022-09-08")) ) gantt_chart(reigns, task = "monarch", start = "from", end = "to", colors = "#a463f2", date_format = "%Y")
A gauge (speedometer) chart displays a single quantitative measure against colored zones (warning and danger) with a needle indicator. By default the needle animates on load, sweeping up from the minimum to the value and settling with a small wobble, like a car dashboard.
gauge_chart( value, min = 0, max = 100, title = "", warning_zone = NULL, warning_color = "orange", danger_zone = NULL, danger_color = "red", arc_bg_color = "#ddd", needle_color = "crimson", pivot_color = "steelblue", title_font_size = 16, value_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", animate = TRUE, animation_duration = 1500, width = NULL, height = NULL )gauge_chart( value, min = 0, max = 100, title = "", warning_zone = NULL, warning_color = "orange", danger_zone = NULL, danger_color = "red", arc_bg_color = "#ddd", needle_color = "crimson", pivot_color = "steelblue", title_font_size = 16, value_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", animate = TRUE, animation_duration = 1500, width = NULL, height = NULL )
value |
Numeric. The current value to display on the gauge. |
min |
Numeric. The minimum value of the gauge. Defaults to 0. |
max |
Numeric. The maximum value of the gauge. Defaults to 100. |
title |
Character. Label shown inside the gauge. Defaults to "". |
warning_zone |
Numeric. The value at which the warning (first) arc begins. Defaults to 75% of max. |
warning_color |
The color of the warning zone arc. Defaults to "orange". |
danger_zone |
Numeric. The value at which the danger (second, critical) arc begins. Defaults to 90% of max. |
danger_color |
The color of the danger zone arc. Defaults to "red". |
arc_bg_color |
The background color of the gauge arc track. Defaults to "#ddd". |
needle_color |
The color of the needle. Defaults to "crimson". |
pivot_color |
The color of the center pivot circle. Defaults to "steelblue". |
title_font_size |
The font size of the gauge title. Defaults to 16. |
value_font_size |
The font size of the current value label. Defaults to 14. |
font |
The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
animate |
Logical. When |
animation_duration |
Numeric. Duration of the needle sweep in milliseconds. Defaults to 1500. |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG gauge chart.
# Basic usage gauge_chart(value = 8, title = "Memory") # Custom warning and danger thresholds gauge_chart( value = 72, min = 0, max = 100, title = "CPU Load", warning_zone = 60, warning_color = "orange", danger_zone = 80, danger_color = "red" ) # Non-percentage range (response time in ms) gauge_chart( value = 530, min = 0, max = 1000, title = "Response (ms)", warning_zone = 400, danger_zone = 700 )# Basic usage gauge_chart(value = 8, title = "Memory") # Custom warning and danger thresholds gauge_chart( value = 72, min = 0, max = 100, title = "CPU Load", warning_zone = 60, warning_color = "orange", danger_zone = 80, danger_color = "red" ) # Non-percentage range (response time in ms) gauge_chart( value = 530, min = 0, max = 1000, title = "Response (ms)", warning_zone = 400, danger_zone = 700 )
Draws a glass of water filled up to a level between 0 and 1. The surface of the water moves gently, bubbles rise from the base and the water sloshes when the mouse moves across the chart. When the chart scrolls into view, the water rises from empty to the level while the percentage above the glass counts up.
glass_fill( fill_level = 0.65, glass_width = NULL, glass_height = NULL, stroke_color = "#555", stroke_width = 2.5, fill_color = "#5aa9e6", render_fill_label = TRUE, label_font_size = NULL, title_text = "Fill level", label_color = "#333", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, ticks = FALSE, waves = TRUE, bubbles = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )glass_fill( fill_level = 0.65, glass_width = NULL, glass_height = NULL, stroke_color = "#555", stroke_width = 2.5, fill_color = "#5aa9e6", render_fill_label = TRUE, label_font_size = NULL, title_text = "Fill level", label_color = "#333", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, ticks = FALSE, waves = TRUE, bubbles = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )
fill_level |
A number between 0 and 1: how full the glass is (values outside are clamped). Defaults to 0.65. |
glass_width |
Optional. The width of the glass (at the rim) in pixels. By default it is 64 percent of the height of the glass. |
glass_height |
Optional. The height of the glass in pixels. By default the glass fills the space available (up to 340 pixels). |
stroke_color |
The colour of the glass. Defaults to "#555". |
stroke_width |
The width of the outline of the glass. Defaults to 2.5. |
fill_color |
The colour of the water. Defaults to "#5aa9e6". |
render_fill_label |
Logical. Show the percentage above the glass. Defaults to TRUE. |
label_font_size |
Optional. The font size of the percentage, a number or a CSS size such as "16px". By default it grows with the glass. |
title_text |
Optional. A caption below the glass. Defaults to "Fill
level"; use |
label_color |
The colour of the percentage, the scale and the target label. Defaults to "#333". |
title_color |
The colour of the caption. Defaults to "#333". |
title_font_size |
The font size of the caption, a number or a CSS size such as "14px". Defaults to 14. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
target |
Optional. A level between 0 and 1 marked with a dashed line and a label. |
ticks |
Logical. Draw a measuring scale (25, 50, 75 and 100 percent) on the glass. Defaults to FALSE. |
waves |
Logical. Animate the surface of the water. Defaults to TRUE. |
bubbles |
Logical. Show bubbles rising in the water. Defaults to TRUE. |
draggable |
Logical. Let the viewer change the level by dragging or with the arrow keys. Defaults to FALSE. |
animate |
Logical. Fill the glass from empty when it first comes into view. Defaults to TRUE. |
bg_col |
The background colour. Defaults to "white". |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
An r2d3 htmlwidget.
Move the mouse across the chart: the water rocks from side to side.
Click the glass: a drop falls into it and splashes.
With draggable = TRUE, drag up or down on the glass to set
the level, or focus the chart (click it or press Tab) and use the arrow
keys (1 percent per press, 10 with Shift).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking the glass sets input$id_clicked to a list with
value, and, with draggable = TRUE, setting a level sets
input$id_value to the new level (a number between 0 and 1). When the
chart is re-rendered with a new level, the water moves from the old level
to the new one.
glass_fill(fill_level = 0.75) glass_fill( fill_level = 0.3, target = 0.8, ticks = TRUE, title_text = "Water intake today" ) glass_fill(0.5, fill_color = "#efb118", draggable = TRUE, title_text = "Drag me")glass_fill(fill_level = 0.75) glass_fill( fill_level = 0.3, target = 0.8, ticks = TRUE, title_text = "Water intake today" ) glass_fill(0.5, fill_color = "#efb118", draggable = TRUE, title_text = "Drag me")
Draws a portrait whose hair grows with a level between 0 and 1: the person is bald at 0 (with a shiny head), gets stubble, a buzz cut, short curls and curly hair, and has a big afro, with an afro pick, at 1. The face smiles more as the hair grows. When the chart scrolls into view, the hair grows from nothing to the level while the percentage above the portrait counts up and the current stage is written under it.
hair_growth( fill_level = 0.5, hair_color = "#2e2530", skin_color = "#a86b4f", shirt_color = "#3f51b5", panel_color = "#dde7ec", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Hair growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )hair_growth( fill_level = 0.5, hair_color = "#2e2530", skin_color = "#a86b4f", shirt_color = "#3f51b5", panel_color = "#dde7ec", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Hair growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )
fill_level |
A number between 0 and 1: how much hair the person has (values outside are clamped). 0 is bald and 1 is a big afro. Defaults to 0.5. |
hair_color |
The colour of the hair and the eyebrows. Defaults to "#2e2530". |
skin_color |
The colour of the skin. Defaults to "#a86b4f". |
shirt_color |
The colour of the turtleneck. Defaults to "#3f51b5". |
panel_color |
The colour of the card behind the portrait. Defaults to
"#dde7ec"; use |
render_fill_label |
Logical. Show the percentage and the stage above the portrait. Defaults to TRUE. |
label_color |
The colour of the percentage, the stage and the target. Defaults to "#333". |
label_font_size |
Optional. The font size of the percentage, a number or a CSS size such as "16px". By default it grows with the chart. |
title_text |
Optional. A caption below the portrait. Defaults to "Hair
growth"; use |
title_color |
The colour of the caption. Defaults to "#333". |
title_font_size |
The font size of the caption, a number or a CSS size such as "14px". Defaults to 14. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
target |
Optional. A level between 0 and 1, drawn as a dashed outline of the hair at that level and written in the top right corner. |
sway |
Logical. Let the hair move gently, the person breathe and blink. Defaults to TRUE. |
draggable |
Logical. Let the viewer change the level by dragging or with the arrow keys. Defaults to FALSE. |
animate |
Logical. Grow the hair from nothing when the chart first comes into view. Defaults to TRUE. |
bg_col |
The background colour. Defaults to "white". |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
An r2d3 htmlwidget.
Move the mouse across the chart: the eyes follow it.
Hover the portrait: the hair bounces a little.
Click the portrait: the hair bounces and the person winks (a bald head shines).
With draggable = TRUE, drag up or down on the portrait to
grow or cut the hair, or focus the chart (click it or press Tab) and use
the arrow keys (1 percent per press, 10 with Shift).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking the portrait sets input$id_clicked to a list with
value and stage, and, with draggable = TRUE, setting a
level sets input$id_value to the new level (a number between 0 and
1). When the chart is re-rendered with a new level, the hair grows or
shrinks from the old level to the new one.
hair_growth(fill_level = 1) hair_growth(0.35, target = 0.8, title_text = "Fundraising goal") hair_growth( fill_level = 0.6, hair_color = "#6b3e26", skin_color = "#f1c7a5", shirt_color = "#3ca951", panel_color = "#fdf1e3", draggable = TRUE, title_text = "Drag up to grow the hair" )hair_growth(fill_level = 1) hair_growth(0.35, target = 0.8, title_text = "Fundraising goal") hair_growth( fill_level = 0.6, hair_color = "#6b3e26", skin_color = "#f1c7a5", shirt_color = "#3ca951", panel_color = "#fdf1e3", draggable = TRUE, title_text = "Drag up to grow the hair" )
Draws a heart filled from the bottom up to a level between 0 and 1. The liquid has a gently moving wavy surface and the heart beats. When the chart scrolls into view, the liquid rises from empty to the level and the percentage counts up with it. The percentage is written inside the heart, in white where the liquid covers it.
heart_fill( fill_level = 0.65, heart_size = NULL, stroke_color = "#b5172b", stroke_width = 3, fill_color = "#e63950", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Fill level", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, waves = TRUE, beat = TRUE, bpm = 60, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )heart_fill( fill_level = 0.65, heart_size = NULL, stroke_color = "#b5172b", stroke_width = 3, fill_color = "#e63950", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Fill level", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, waves = TRUE, beat = TRUE, bpm = 60, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )
fill_level |
A number between 0 and 1: how full the heart is (values outside are clamped). Defaults to 0.65. |
heart_size |
Optional. The width of the heart in pixels. By default the heart fills the space available (up to 360 pixels). |
stroke_color |
The colour of the outline. Defaults to "#b5172b". |
stroke_width |
The width of the outline. Defaults to 3. |
fill_color |
The colour of the liquid. Defaults to "#e63950". The empty part of the heart is a pale shade of it. |
render_fill_label |
Logical. Show the percentage inside the heart. Defaults to TRUE. |
label_color |
The colour of the percentage (where the liquid does not cover it) and of the target label. Defaults to "#333". |
label_font_size |
Optional. The font size of the percentage, a number or a CSS size such as "16px". By default it grows with the heart. |
title_text |
Optional. A caption below the heart. Defaults to
"Fill level"; use |
title_color |
The colour of the caption. Defaults to "#333". |
title_font_size |
The font size of the caption, a number or a CSS size such as "14px". Defaults to 14. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
target |
Optional. A level between 0 and 1 marked with a dashed line and a label. |
waves |
Logical. Animate the surface of the liquid. Defaults to TRUE. |
beat |
Logical. Make the heart beat. Defaults to TRUE. |
bpm |
The heart rate, in beats per minute. Defaults to 60. |
draggable |
Logical. Let the viewer change the level by dragging or with the arrow keys. Defaults to FALSE. |
animate |
Logical. Fill the heart from empty when it first comes into view. Defaults to TRUE. |
bg_col |
The background colour. Defaults to "white". |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
An r2d3 htmlwidget.
Hover the heart: it beats faster.
Click the heart: small hearts float up from where you clicked.
With draggable = TRUE, drag up or down on the heart to set
the level, or focus the chart (click it or press Tab) and use the arrow
keys (1 percent per press, 10 with Shift).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking the heart sets input$id_clicked to a list with
value, and, with draggable = TRUE, setting a level sets
input$id_value to the new level (a number between 0 and 1). When the
chart is re-rendered with a new level, the liquid moves from the old level
to the new one.
heart_fill(fill_level = 0.9) heart_fill( fill_level = 0.4, target = 0.75, fill_color = "#ff8ab7", stroke_color = "#c2185b", title_text = "Daily activity goal" ) heart_fill(0.55, draggable = TRUE, title_text = "Drag me")heart_fill(fill_level = 0.9) heart_fill( fill_level = 0.4, target = 0.75, fill_color = "#ff8ab7", stroke_color = "#c2185b", title_text = "Daily activity goal" ) heart_fill(0.55, draggable = TRUE, title_text = "Drag me")
Draws a grid of coloured cells, one per combination of two categorical
columns, coloured by a value (or by the number of rows when value is
NULL). Rows sharing the same pair are aggregated. With a
midpoint, the colours diverge around it (useful for correlations or
changes); with cluster = TRUE, the rows and the columns are reordered
by hierarchical clustering so that similar ones sit together.
heatmap_chart( data, x, y, value = NULL, aggregate = c("sum", "mean", "median", "min", "max"), colors = NULL, midpoint = NULL, cluster = FALSE, show_values = NULL, value_format = ",.2~f", cell_gap = 1, cell_radius = 2, na_col = "#f2f2f2", legend = TRUE, x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 11, y_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )heatmap_chart( data, x, y, value = NULL, aggregate = c("sum", "mean", "median", "min", "max"), colors = NULL, midpoint = NULL, cluster = FALSE, show_values = NULL, value_format = ",.2~f", cell_gap = 1, cell_radius = 2, na_col = "#f2f2f2", legend = TRUE, x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 11, y_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
A data frame. |
x, y
|
The names of the columns giving the columns and the rows of the grid. Factor levels give the order. |
value |
Optional. The name of a numeric column giving the colour. When
|
aggregate |
How to combine several rows of the same pair: |
colors |
The colour ramp, from low to high (two colours or more). By
default a light to dark blue ramp, or red - white - blue with a
|
midpoint |
Optional. A value at the centre of a diverging colour ramp (e.g. 0 for correlations). The ramp is symmetric around it. |
cluster |
Logical. Reorder the rows and columns by hierarchical
clustering ( |
show_values |
Logical. Write the values in the cells. By default they are shown when the cells are large enough. |
value_format |
A d3 format for the values. Defaults to ",.2~f". |
cell_gap |
The gap between cells in pixels. Defaults to 1. |
cell_radius |
The corner radius of the cells in pixels. Defaults to 2. |
na_col |
The colour of missing pairs. Defaults to "#f2f2f2". |
legend |
Logical. Show the colour legend. Defaults to TRUE. |
x_title, y_title
|
Optional. The titles of the axes. |
axis_title_font_size |
The font size of the axis titles. Defaults to 12. |
x_font_size, y_font_size
|
The font sizes of the labels. Default to 11. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Fade the cells in when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text. Defaults to "#333333". |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a cell to see its value, outline it, highlight its row and column
labels and mark it on the colour legend. Cells fade in diagonally when the
chart is drawn. Inside Shiny, clicking a cell sets
input$<id>_clicked to a list with x, y and
value.
# A correlation matrix cors <- as.data.frame(as.table(cor(mtcars))) names(cors) <- c("var1", "var2", "correlation") heatmap_chart(cors, x = "var1", y = "var2", value = "correlation", midpoint = 0, cluster = TRUE, title = "Correlations in mtcars") # Average temperature by month and day of the week aq <- airquality aq$Month <- factor(month.abb[aq$Month], levels = month.abb[5:9]) aq$Week <- paste("Week", (aq$Day - 1) %/% 7 + 1) heatmap_chart(aq, x = "Month", y = "Week", value = "Temp", aggregate = "mean", colors = c("#fff3d6", "#ffb15c", "#d6402b"), value_format = ".0f", title = "Temperature in New York (F)") # Counts of two categorical variables heatmap_chart(ggplot2::mpg, x = "class", y = "manufacturer", show_values = TRUE)# A correlation matrix cors <- as.data.frame(as.table(cor(mtcars))) names(cors) <- c("var1", "var2", "correlation") heatmap_chart(cors, x = "var1", y = "var2", value = "correlation", midpoint = 0, cluster = TRUE, title = "Correlations in mtcars") # Average temperature by month and day of the week aq <- airquality aq$Month <- factor(month.abb[aq$Month], levels = month.abb[5:9]) aq$Week <- paste("Week", (aq$Day - 1) %/% 7 + 1) heatmap_chart(aq, x = "Month", y = "Week", value = "Temp", aggregate = "mean", colors = c("#fff3d6", "#ffb15c", "#d6402b"), value_format = ".0f", title = "Temperature in New York (F)") # Counts of two categorical variables heatmap_chart(ggplot2::mpg, x = "class", y = "manufacturer", show_values = TRUE)
A hexbin plot is a two-dimensional histogram: the x/y plane is tiled with a grid of regular hexagons, every observation is assigned to the hexagon it falls into, and each hexagon is colored by the number of observations it contains. It is a readable alternative to a scatter plot when there are too many points to see individually (overplotting), because dense regions remain distinguishable instead of turning into a solid blob.
The look is inspired by the hexbin transform of the Observable Plot
library: light gridlines, a sequential color scale with a continuous
legend, and an optional mode where the hexagon size (area) also
encodes the count. Binning is done in pixel space, so the hexagons are
always regular regardless of the units of x and y.
The plot is interactive: hovering a hexagon outlines it, marks its count
on the color legend and (when tooltip = TRUE) shows a tooltip with
the bin count, its share of all observations, and the x/y range covered
by the hexagon.
hexbin_plot( data, x, y, bin_width = 12, size_by_count = FALSE, color_palette = "YlGnBu", reverse_colors = FALSE, color_scale = c("linear", "sqrt", "log"), legend = TRUE, legend_title = "Count", tooltip = TRUE, hover = TRUE, animate = TRUE, opacity = 1, stroke = "white", stroke_width = 0.5, grid = TRUE, grid_col = "#e5e5e5", x_title = NULL, y_title = NULL, x_title_font_size = 13, y_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )hexbin_plot( data, x, y, bin_width = 12, size_by_count = FALSE, color_palette = "YlGnBu", reverse_colors = FALSE, color_scale = c("linear", "sqrt", "log"), legend = TRUE, legend_title = "Count", tooltip = TRUE, hover = TRUE, animate = TRUE, opacity = 1, stroke = "white", stroke_width = 0.5, grid = TRUE, grid_col = "#e5e5e5", x_title = NULL, y_title = NULL, x_title_font_size = 13, y_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
x |
The name of the numeric column mapped to the horizontal axis. |
y |
The name of the numeric column mapped to the vertical axis. |
bin_width |
The radius of each hexagon in pixels (distance from its
center to a corner). Larger values give fewer, coarser bins. Defaults to
|
size_by_count |
Logical. When |
color_palette |
The name of a D3 sequential color interpolator,
without the |
reverse_colors |
Logical. Whether to reverse the direction of the
color palette. Defaults to |
color_scale |
How counts are mapped to colors: |
legend |
Logical. Whether to draw the continuous color legend.
Defaults to |
legend_title |
Title of the color legend. Defaults to |
tooltip |
Logical. Whether to show a tooltip when a hexagon is
hovered. Defaults to |
hover |
Logical. When |
animate |
Logical. When |
opacity |
Fill opacity of the hexagons (0 to 1). Defaults to |
stroke |
Stroke color of the hexagons. Defaults to |
stroke_width |
Stroke width of the hexagons in pixels. Defaults to
|
grid |
Logical. Whether to draw light gridlines behind the hexagons.
Defaults to |
grid_col |
Color of the gridlines. Defaults to |
x_title |
Optional. Title of the x-axis. Defaults to the value of
|
y_title |
Optional. Title of the y-axis. Defaults to the value of
|
x_title_font_size |
Font size of the x-axis title. Defaults to |
y_title_font_size |
Font size of the y-axis title. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
x_font_size |
Font size of the x-axis tick labels. Defaults to |
y_font_size |
Font size of the y-axis tick labels. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of axis lines, ticks, labels and titles. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG hexbin plot.
# Old Faithful geyser: eruption duration vs waiting time hexbin_plot( data = faithful, x = "waiting", y = "eruptions", bin_width = 14, x_title = "Waiting time to next eruption (min)", y_title = "Eruption duration (min)", title = "Old Faithful eruptions" ) # 10,000 diamonds: carat vs price, with a log color scale library(ggplot2) # for the diamonds dataset set.seed(1) dsample <- diamonds[sample(nrow(diamonds), 10000), ] hexbin_plot( data = dsample, x = "carat", y = "price", bin_width = 8, color_palette = "Viridis", color_scale = "log", x_title = "Carat", y_title = "Price (USD)", title = "Diamond price by carat" ) # Hexagon size encodes the count as well as the color set.seed(42) pts <- data.frame( a = c(rnorm(1500, 0, 1), rnorm(800, 3, 0.6)), b = c(rnorm(1500, 0, 1), rnorm(800, 2, 0.6)) ) hexbin_plot( data = pts, x = "a", y = "b", bin_width = 13, size_by_count = TRUE, color_palette = "Magma", reverse_colors = TRUE, title = "Two bivariate normal clusters" )# Old Faithful geyser: eruption duration vs waiting time hexbin_plot( data = faithful, x = "waiting", y = "eruptions", bin_width = 14, x_title = "Waiting time to next eruption (min)", y_title = "Eruption duration (min)", title = "Old Faithful eruptions" ) # 10,000 diamonds: carat vs price, with a log color scale library(ggplot2) # for the diamonds dataset set.seed(1) dsample <- diamonds[sample(nrow(diamonds), 10000), ] hexbin_plot( data = dsample, x = "carat", y = "price", bin_width = 8, color_palette = "Viridis", color_scale = "log", x_title = "Carat", y_title = "Price (USD)", title = "Diamond price by carat" ) # Hexagon size encodes the count as well as the color set.seed(42) pts <- data.frame( a = c(rnorm(1500, 0, 1), rnorm(800, 3, 0.6)), b = c(rnorm(1500, 0, 1), rnorm(800, 2, 0.6)) ) hexbin_plot( data = pts, x = "a", y = "b", bin_width = 13, size_by_count = TRUE, color_palette = "Magma", reverse_colors = TRUE, title = "Two bivariate normal clusters" )
Shows the distribution of a numeric variable as bars counting the
observations in bins of equal width. The bins are computed in the browser,
so their number can be changed from the chart. With group, the bars
are split by group, stacked or overlaid. A density curve, mean and median
lines, reference lines and a rug can be added, and a summary of the data
(number of observations, mean, median, standard deviation) is shown above
the bars.
histogram( x, bins = 30, fill = NULL, x_font_size = 11, y_font_size = 11, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = NULL, axis_col = "#333333", width = NULL, height = NULL, data = NULL, group = NULL, bin_width = NULL, breaks = NULL, position = c("stacked", "overlay"), stat = c("count", "percent", "density"), density = FALSE, stats = NULL, ref_lines = NULL, rug = FALSE, summary = TRUE, corner_radius = 2, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, x_format = NULL, x_prefix = "", x_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )histogram( x, bins = 30, fill = NULL, x_font_size = 11, y_font_size = 11, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = NULL, axis_col = "#333333", width = NULL, height = NULL, data = NULL, group = NULL, bin_width = NULL, breaks = NULL, position = c("stacked", "overlay"), stat = c("count", "percent", "density"), density = FALSE, stats = NULL, ref_lines = NULL, rug = FALSE, summary = TRUE, corner_radius = 2, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, x_format = NULL, x_prefix = "", x_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )
x |
A numeric vector, or, when |
bins |
The approximate number of bins. The bins are given round
widths (1, 2, 2.5 or 5 times a power of ten), so the actual number can
differ slightly. Defaults to 30. Ignored when |
fill |
The colour of the bars. A single colour, or, with |
x_font_size |
The font size of the x-axis labels. Defaults to 11. |
y_font_size |
The font size of the y-axis labels. Defaults to 11. |
x_ticks |
Optional. The approximate number of x-axis ticks. |
y_ticks |
Optional. The approximate number of y-axis ticks. |
x_title |
Optional. The title of the x-axis. Defaults to the name of
the variable (when it can be found); use |
x_title_font_size |
The font size of the x-axis title. Defaults to 13. |
y_title |
Optional. The title of the y-axis, drawn above it. Defaults
to "Count", "Percent" or "Density"; use |
y_title_font_size |
The font size of the y-axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
stroke |
Optional. The stroke colour of the bars. |
stroke_width |
Optional. The stroke width of the bars. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
opacity |
The opacity of the bars (from 0 to 1). Defaults to 1, or 0.5 for overlaid groups. |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
data |
Optional. A data frame; |
group |
Optional. A vector of the same length as |
bin_width |
Optional. The width of the bins, in the units of |
breaks |
Optional. A numeric vector of bin edges, for bins of unequal width (the bars are then scaled by density so their areas stay comparable). Values outside the edges are left out. The number of bins cannot be changed from the chart. |
position |
How groups are drawn: |
stat |
What the bar heights show: |
density |
Add a density curve: |
stats |
Optional. Summary lines to draw across the bars: any of
|
ref_lines |
Optional. Numeric values drawn as dashed vertical lines (e.g. a threshold or a target); names are used as labels. |
rug |
Logical. Draw a small tick under the bars for every observation
(up to 5,000 observations). Defaults to |
summary |
Logical. Show the number of observations, the mean, the
median and the standard deviation above the bars (or those of the
selected range). Defaults to |
corner_radius |
The radius of the rounded top corners of the bars, in pixels. Defaults to 2; use 0 for square bars. |
legend |
Logical. Show the legend (with |
controls |
Logical. Show the buttons that change the bins, the
counts / percentages and the layout. Defaults to |
tooltip |
Logical. Show a tooltip when hovering the bins. Defaults to
|
animate |
Logical. Grow the bars when the chart is first drawn.
Defaults to |
x_format |
Optional. A D3 format string for the values of |
x_prefix, x_suffix
|
Optional. Text added before and after the values of
|
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
grid_col |
The colour of the horizontal grid lines. Defaults to
"#e9e9e9"; use |
An interactive SVG histogram (an r2d3 htmlwidget).
Hover a bin to see its range, its count, its share of the total and
the share of the observations below its upper edge; with group,
the tooltip lists every group.
The buttons at the top right change the number of bins (− / +),
switch between counts and percentages and, with group, between
stacked and overlaid bars.
Drag across the bars to select a range: the summary then describes the selected observations. "Zoom" re-bins the data within the range; double-click or "Reset zoom" goes back to the full range.
Click a legend entry to hide or show a group, double-click it to isolate it.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a bin sets input$id_clicked to a list with from,
to, count and group; selecting a range sets
input$id_selected to a list with from, to and
count (NULL when the selection is cleared). The number of
bins, the layout, the hidden groups and the zoom are kept when the chart is
re-rendered.
histogram( x = mtcars$mpg, bins = 10, title = "Fuel economy", x_title = "Miles per gallon" ) library(ggplot2) # needed for the diamonds and mpg data frames # A long-tailed variable, with its density and summary lines histogram( x = "price", data = diamonds, bins = 50, density = TRUE, stats = c("mean", "median"), x_prefix = "$", x_format = ",.0f", title = "Diamond prices" ) # Groups compared on a percentage scale histogram( x = "hwy", data = mpg, group = "drv", position = "overlay", stat = "percent", bin_width = 2, density = TRUE, title = "Highway fuel economy by drive train" )histogram( x = mtcars$mpg, bins = 10, title = "Fuel economy", x_title = "Miles per gallon" ) library(ggplot2) # needed for the diamonds and mpg data frames # A long-tailed variable, with its density and summary lines histogram( x = "price", data = diamonds, bins = 50, density = TRUE, stats = c("mean", "median"), x_prefix = "$", x_format = ",.0f", title = "Diamond prices" ) # Groups compared on a percentage scale histogram( x = "hwy", data = mpg, group = "drv", position = "overlay", stat = "percent", bin_width = 2, density = TRUE, title = "Highway fuel economy by drive train" )
The horizontal version of bar_chart(): categories are listed
down the left side, which suits many categories and long labels. It has
the same features (groups, stacking, aggregation, value labels, sorting
and layout buttons, tooltips, legend); see bar_chart() for
the interactions and the Shiny inputs.
horz_bar_chart( data, label, value = NULL, fill = NULL, sort = "none", padding_width = 0.2, stroke = NULL, stroke_width = NULL, bg_col = "white", value_ticks = NULL, value_font_size = 11, label_font_size = 12, value_title = NULL, value_title_font_size = 13, label_title = NULL, label_title_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", title = NULL, title_font_size = 20, opacity = 1, axis_col = "#333333", width = NULL, height = NULL, group = NULL, position = c("grouped", "stacked", "percent"), agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, corner_radius = 3, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )horz_bar_chart( data, label, value = NULL, fill = NULL, sort = "none", padding_width = 0.2, stroke = NULL, stroke_width = NULL, bg_col = "white", value_ticks = NULL, value_font_size = 11, label_font_size = 12, value_title = NULL, value_title_font_size = 13, label_title = NULL, label_title_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", title = NULL, title_font_size = 20, opacity = 1, axis_col = "#333333", width = NULL, height = NULL, group = NULL, position = c("grouped", "stacked", "percent"), agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, corner_radius = 3, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )
data |
The data frame containing the variables to consider. |
label |
The name of the categorical variable, listed on the y-axis. |
value |
The name of the numeric variable, plotted along the x-axis.
When |
fill |
The colour of the bars. A single colour, or, without
|
sort |
The initial order of the bars: |
padding_width |
The space between bars, from 0 to 0.99. Defaults to 0.2. |
stroke |
Optional. The stroke colour of the bars. |
stroke_width |
Optional. The stroke width of the bars. |
bg_col |
The background color of the SVG. Defaults to "white". |
value_ticks |
Optional. The approximate number of value axis ticks. |
value_font_size |
The font size of the value axis labels. Defaults to 11. |
label_font_size |
The font size of the category labels. Defaults to 12. |
value_title |
Optional. The title of the value axis. Defaults to the
name of |
value_title_font_size |
The font size of the value axis title. Defaults to 13. |
label_title |
Optional. The title of the category axis, drawn above the labels. |
label_title_font_size |
The font size of the category axis title. Defaults to 13. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
opacity |
The opacity of the bars (from 0 to 1). Defaults to 1. |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
group |
Optional. The name of a column that splits each bar into groups (one colour per group, with a clickable legend). |
position |
How groups are drawn: |
agg |
How rows with the same category (and group) are combined:
|
labels |
Logical. Write the values on the bars (labels that do not fit
are skipped). Defaults to |
highlight |
Optional. A character vector of categories to emphasise;
the other bars are drawn in grey (or faded, with |
ref_lines |
Optional. Numeric values drawn as dashed reference lines across the bars (e.g. a target or an average); names are used as labels. |
negative_fill |
Optional. The colour of negative bars (without
|
corner_radius |
The radius of the rounded bar ends, in pixels. Defaults to 3; use 0 for square bars. |
legend |
Logical. Show the legend. When |
controls |
Logical. Show the layout and sort buttons. Defaults to
|
tooltip |
Logical. Show a tooltip on hover. Defaults to |
animate |
Logical. Animate the bars when the chart is first drawn.
Defaults to |
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
grid_col |
The colour of the grid lines. Defaults to "#e9e9e9"; use
|
An interactive SVG horizontal bar chart (an r2d3 htmlwidget).
library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for the data wrangling process mpg %>% group_by(manufacturer) %>% summarise(median_hwy = median(hwy)) %>% horz_bar_chart( label = "manufacturer", value = "median_hwy", sort = "descending", title = "Median highway miles per gallon" ) # 100% stacked bars from raw rows horz_bar_chart( data = mpg, label = "manufacturer", group = "drv", position = "percent", sort = "descending", title = "Drive train by manufacturer" ) # Positive and negative values change <- data.frame( country = c("Spain", "France", "Italy", "Germany", "Poland", "Sweden"), growth = c(2.4, 0.9, -0.3, -0.6, 3.1, 1.2) ) horz_bar_chart( change, label = "country", value = "growth", sort = "descending", negative_fill = "#ff725c", value_suffix = "%", value_title = "GDP growth", title = "Annual GDP growth" )library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for the data wrangling process mpg %>% group_by(manufacturer) %>% summarise(median_hwy = median(hwy)) %>% horz_bar_chart( label = "manufacturer", value = "median_hwy", sort = "descending", title = "Median highway miles per gallon" ) # 100% stacked bars from raw rows horz_bar_chart( data = mpg, label = "manufacturer", group = "drv", position = "percent", sort = "descending", title = "Drive train by manufacturer" ) # Positive and negative values change <- data.frame( country = c("Spain", "France", "Italy", "Germany", "Poland", "Sweden"), growth = c(2.4, 0.9, -0.3, -0.6, 3.1, 1.2) ) horz_bar_chart( change, label = "country", value = "growth", sort = "descending", negative_fill = "#ff725c", value_suffix = "%", value_title = "GDP growth", title = "Annual GDP growth" )
The horizontal version of lollipop_chart(): categories are
listed down the left side, which suits many categories and long labels. It
has the same features (groups, aggregation, value labels, sort buttons,
tooltips, legend); see lollipop_chart() for the interactions
and the Shiny inputs.
horz_lollipop( data, label, value = NULL, sort = "none", bg_col = "white", value_ticks = NULL, label_ticks = NULL, value_font_size = 11, label_font_size = 12, font = "Verdana, Geneva, Tahoma, sans-serif", value_title = NULL, value_title_font_size = 13, label_title = NULL, label_title_font_size = 13, title = NULL, title_font_size = 20, line_stroke = NULL, line_stroke_width = 2, circle_fill = NULL, circle_stroke = NULL, circle_stroke_width = 1.5, circle_radius = 6, axis_col = "#333333", width = NULL, height = NULL, group = NULL, agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9", opacity = 1 )horz_lollipop( data, label, value = NULL, sort = "none", bg_col = "white", value_ticks = NULL, label_ticks = NULL, value_font_size = 11, label_font_size = 12, font = "Verdana, Geneva, Tahoma, sans-serif", value_title = NULL, value_title_font_size = 13, label_title = NULL, label_title_font_size = 13, title = NULL, title_font_size = 20, line_stroke = NULL, line_stroke_width = 2, circle_fill = NULL, circle_stroke = NULL, circle_stroke_width = 1.5, circle_radius = 6, axis_col = "#333333", width = NULL, height = NULL, group = NULL, agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9", opacity = 1 )
data |
The data frame containing the variables to consider. |
label |
The name of the categorical variable, listed on the y-axis. |
value |
The name of the numeric variable, plotted along the x-axis.
When |
sort |
The initial order of the lollipops: |
bg_col |
The background color of the SVG. Defaults to "white". |
value_ticks |
Optional. The approximate number of value axis ticks. |
label_ticks |
Not used; kept for compatibility. |
value_font_size |
The font size of the value axis labels. Defaults to 11. |
label_font_size |
The font size of the category labels. Defaults to 12. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
value_title |
Optional. The title of the value axis. Defaults to the
name of |
value_title_font_size |
The font size of the value axis title. Defaults to 13. |
label_title |
Optional. The title of the category axis, drawn above the labels. |
label_title_font_size |
The font size of the category axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
line_stroke |
Optional. The colour of the stems. Defaults to the colour of the dots. |
line_stroke_width |
The width of the stems, in pixels. Defaults to 2. |
circle_fill |
The colour of the dots. A single colour, or, without
|
circle_stroke |
Optional. The colour of the ring around the dots. Defaults to the background colour. |
circle_stroke_width |
The width of the ring around the dots. Defaults to 1.5. |
circle_radius |
The radius of the dots, in pixels. Defaults to 6. Dots are made smaller when there is not enough room for them. |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
group |
Optional. The name of a column that splits each category into groups, drawn side by side (one colour per group, with a clickable legend). |
agg |
How rows with the same category (and group) are combined:
|
labels |
Logical. Write the values next to the dots (when every label
fits). Defaults to |
highlight |
Optional. A character vector of categories to emphasise;
the other lollipops are drawn in grey (or faded, with |
ref_lines |
Optional. Numeric values drawn as dashed reference lines across the bars (e.g. a target or an average); names are used as labels. |
negative_fill |
Optional. The colour of negative lollipops (without
|
legend |
Logical. Show the legend. When |
controls |
Logical. Show the sort buttons. Defaults to |
tooltip |
Logical. Show a tooltip on hover. Defaults to |
animate |
Logical. Animate the lollipops when the chart is first
drawn. Defaults to |
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
grid_col |
The colour of the grid lines. Defaults to "#e9e9e9"; use
|
opacity |
The opacity of the lollipops (from 0 to 1). Defaults to 1. |
An interactive SVG horizontal lollipop chart (an r2d3 htmlwidget).
library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for data wrangling mpg %>% group_by(manufacturer) %>% summarise(median_cty = median(cty)) %>% horz_lollipop( label = "manufacturer", value = "median_cty", sort = "descending", title = "Median city miles per gallon" ) # Count rows, with an average line counts <- count(mpg, manufacturer) horz_lollipop( mpg, label = "manufacturer", sort = "descending", ref_lines = c(Average = mean(counts$n)), title = "Models per manufacturer" ) # Positive and negative values change <- data.frame( country = c("Spain", "France", "Italy", "Germany", "Poland", "Sweden"), growth = c(2.4, 0.9, -0.3, -0.6, 3.1, 1.2) ) horz_lollipop( change, label = "country", value = "growth", sort = "descending", negative_fill = "#ff725c", value_suffix = "%", value_title = "GDP growth", title = "Annual GDP growth" )library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for data wrangling mpg %>% group_by(manufacturer) %>% summarise(median_cty = median(cty)) %>% horz_lollipop( label = "manufacturer", value = "median_cty", sort = "descending", title = "Median city miles per gallon" ) # Count rows, with an average line counts <- count(mpg, manufacturer) horz_lollipop( mpg, label = "manufacturer", sort = "descending", ref_lines = c(Average = mean(counts$n)), title = "Models per manufacturer" ) # Positive and negative values change <- data.frame( country = c("Spain", "France", "Italy", "Germany", "Poland", "Sweden"), growth = c(2.4, 0.9, -0.3, -0.6, 3.1, 1.2) ) horz_lollipop( change, label = "country", value = "growth", sort = "descending", negative_fill = "#ff725c", value_suffix = "%", value_title = "GDP growth", title = "Annual GDP growth" )
Draws the answers to survey questions on an ordered scale (from "Strongly disagree" to "Strongly agree", from "Very bad" to "Very good", ...) as diverging stacked bars: the negative answers go to the left of a centre line and the positive ones to the right, with a neutral answer (the middle level of an odd scale) split across the line. The share of negative and positive answers is written at both ends of each bar.
likert_chart( data, question, response, value = NULL, levels = NULL, colors = NULL, sort = c("none", "positive", "negative"), show_values = TRUE, show_totals = TRUE, bar_height = 0.7, label_font_size = 11, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )likert_chart( data, question, response, value = NULL, levels = NULL, colors = NULL, sort = c("none", "positive", "negative"), show_values = TRUE, show_totals = TRUE, bar_height = 0.7, label_font_size = 11, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
A data frame, with one row per answer (or one row per question
and answer with a |
question |
The name of the column with the questions (or items). |
response |
The name of the column with the answers. |
value |
Optional. The name of a numeric column of counts. When
|
levels |
Optional. The answers in order, from the most negative to the
most positive. Defaults to the factor levels of |
colors |
Optional. One colour per level. By default a red - grey - blue scale. |
sort |
How to order the questions: |
show_values |
Logical. Write the share of each answer in its segment when it fits. Defaults to TRUE. |
show_totals |
Logical. Write the share of negative and positive answers at the ends of each bar. Defaults to TRUE. |
bar_height |
The height of the bars as a share of the space of each question. Defaults to 0.7. |
label_font_size |
The font size of the questions. Defaults to 11. |
legend |
Logical. Show the legend. Defaults to TRUE. |
legend_font_size |
The font size of the legend. Defaults to 11. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Grow the bars when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text. Defaults to "#333333". |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a segment to see its share and count, while the same answer is
highlighted for every question; hover the legend to highlight an answer.
The bars grow from the centre line when the chart is drawn. Inside Shiny,
clicking a segment sets input$<id>_clicked to a list with
question, response, count and percent.
survey <- data.frame( question = rep(c("The product is easy to use", "Support answers quickly", "The price is fair", "I would recommend it"), each = 5), answer = rep(c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"), times = 4), n = c(4, 10, 18, 45, 23, 12, 20, 25, 28, 15, 20, 30, 22, 20, 8, 5, 8, 15, 40, 32) ) likert_chart(survey, question = "question", response = "answer", value = "n", sort = "positive", title = "Customer survey") # One row per answer, a four-point scale without a neutral answer set.seed(1) scale4 <- c("Never", "Rarely", "Often", "Always") habits <- data.frame( habit = rep(c("Cook at home", "Walk to work", "Read before bed"), each = 60), answer = c(sample(scale4, 60, TRUE, c(1, 2, 4, 3)), sample(scale4, 60, TRUE, c(4, 3, 2, 1)), sample(scale4, 60, TRUE, c(2, 3, 3, 2))) ) likert_chart(habits, question = "habit", response = "answer", levels = scale4, colors = c("#d6402b", "#ffb15c", "#6cc5b0", "#1f7a63"))survey <- data.frame( question = rep(c("The product is easy to use", "Support answers quickly", "The price is fair", "I would recommend it"), each = 5), answer = rep(c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"), times = 4), n = c(4, 10, 18, 45, 23, 12, 20, 25, 28, 15, 20, 30, 22, 20, 8, 5, 8, 15, 40, 32) ) likert_chart(survey, question = "question", response = "answer", value = "n", sort = "positive", title = "Customer survey") # One row per answer, a four-point scale without a neutral answer set.seed(1) scale4 <- c("Never", "Rarely", "Often", "Always") habits <- data.frame( habit = rep(c("Cook at home", "Walk to work", "Read before bed"), each = 60), answer = c(sample(scale4, 60, TRUE, c(1, 2, 4, 3)), sample(scale4, 60, TRUE, c(4, 3, 2, 1)), sample(scale4, 60, TRUE, c(2, 3, 3, 2))) ) likert_chart(habits, question = "habit", response = "answer", levels = scale4, colors = c("#d6402b", "#ffb15c", "#6cc5b0", "#1f7a63"))
Draws one or several time series as lines, with the interactions that people who work with time series expect: a crosshair tooltip that shows every series at the hovered date, a clickable legend, direct labels at the end of each line, range buttons (1M, 6M, YTD, 1Y, ...), a navigator with a brush under the chart, drag-to-zoom and double-click to reset. The y axis rescales to the data in view whenever you zoom.
line_chart( data, x = NULL, y = NULL, group = NULL, lower = NULL, upper = NULL, colors = NULL, stroke = NULL, stroke_width = 2, curve = "curveLinear", opacity = 1, area = FALSE, points = FALSE, y_scale = c("linear", "log"), y_zero = NULL, transform = c("none", "index", "percent"), index_base = 100, roll_mean = NULL, show_raw = TRUE, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", grid_col = "#e9e9e9", axis_col = "#333333", width = NULL, height = NULL )line_chart( data, x = NULL, y = NULL, group = NULL, lower = NULL, upper = NULL, colors = NULL, stroke = NULL, stroke_width = 2, curve = "curveLinear", opacity = 1, area = FALSE, points = FALSE, y_scale = c("linear", "log"), y_zero = NULL, transform = c("none", "index", "percent"), index_base = 100, roll_mean = NULL, show_raw = TRUE, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", grid_col = "#e9e9e9", axis_col = "#333333", width = NULL, height = NULL )
data |
A data frame, or a |
x |
The time variable. Can be a |
y |
The value variable(s). One column name, or several column names
to draw one line per column (wide data). For a univariate |
group |
Optional. For long data, the column whose values name the
series (one line per value). Cannot be combined with several |
lower, upper
|
Optional. Columns holding the lower and upper bounds of
a confidence or forecast interval, drawn as a shaded ribbon around the
line. With several |
colors |
Optional. Colors of the series. Either an unnamed vector (recycled in series order) or a vector named by series. Defaults to a built-in 10-color palette. |
stroke |
The color of the line when there is a single series. When
|
stroke_width |
The width of the lines. Defaults to 2. |
curve |
The line's curve type. A complete list can be found here <https://github.com/d3/d3-shape#curves>. Defaults to 'curveLinear'; 'curveMonotoneX' gives smooth lines that never overshoot the data. |
opacity |
The opacity of the lines (from 0 to 1). Defaults to 1. |
area |
Logical. Fill the area under each line with a soft gradient.
Defaults to |
points |
Logical. Draw a marker on every data point. Defaults to
|
y_scale |
Either "linear" (default) or "log". |
y_zero |
Logical. Force the y axis to include 0. When |
transform |
How values are displayed: "none" (default), "index"
(each series rebased to |
index_base |
The value series are rebased to when
|
roll_mean |
Optional. A window size (number of observations). When given, a trailing moving average is drawn as the main line. |
show_raw |
Logical. When |
events |
Optional. Dates to mark with a vertical line: either a vector of dates (names are used as labels) or a data frame whose first column holds the dates and whose second column (optional) holds labels. |
bands |
Optional. Periods to shade, as a data frame whose first two columns are the start and end dates. An optional third column holds the labels and an optional fourth column the fill colors. |
h_lines |
Optional. Numeric reference values drawn as horizontal
dashed lines (names are used as labels). Only drawn when
|
legend |
Logical. Show the interactive legend (click to hide or show
a series, double-click to isolate it). When |
end_labels |
Logical. Label each line at its last visible point. When
|
tooltip |
Logical. Show the crosshair and the tooltip on hover.
Defaults to |
navigator |
Logical. Show the navigator (a miniature of the full
series with a brush to select the visible range) under the chart.
Defaults to |
range_buttons |
Logical. Show range buttons (1M, 6M, YTD, 1Y, 5Y,
All, ...), chosen from the length and frequency of the data. Only used
with dates. Defaults to |
zoom |
Logical. Drag horizontally on the chart to zoom into a range;
double-click to reset. Defaults to |
animate |
Logical. Draw the lines in with an animation on first
render. Defaults to |
value_format |
Optional. A d3-format string for values in the tooltip
(see <https://github.com/d3/d3-format>). Defaults to ",.2~f", or "+.2~%"
with |
value_prefix, value_suffix
|
Optional. Text placed before and after the values on the y axis and in the tooltip, for example "$" or " km". |
date_format |
Optional. A d3-time-format string for the date in the
tooltip (see <https://github.com/d3/d3-time-format>). When |
x_ticks |
Optional. The approximate number of x-axis ticks. |
y_ticks |
Optional. The approximate number of y-axis ticks. |
x_title |
Optional. The title of the x-axis. |
x_title_font_size |
The font size of the x-axis title. Defaults to 13. |
y_title |
Optional. The title of the y-axis, shown above the axis. |
y_title_font_size |
The font size of the y-axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
subtitle |
Optional. A subtitle shown under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
x_font_size, y_font_size
|
The font size of the axis tick labels. Defaults to 11. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
grid_col |
The color of the horizontal grid lines. Defaults to "#e9e9e9". |
axis_col |
The color of the axis text, ticks and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
Series can be given in three ways:
one column: y = "value";
wide data: several columns, y = c("a", "b", "c");
long data: one value column and a group column that
names the series.
A ts or mts object (for example AirPassengers or
EuStockMarkets) can also be passed directly as data, in which
case x and y are not needed. Monthly, quarterly and yearly
series get exact calendar dates; for other frequencies (for example the
260 trading days a year of EuStockMarkets) the dates are
interpolated from the decimal time index, so pass a data frame with a real
date column when exact dates matter.
Time-series extras: transform = "index" rebases every series to 100
at the start of the visible range (or "percent" for the change since
then), roll_mean overlays a moving average, lower /
upper draw a confidence or forecast ribbon, bands shade
periods such as recessions, events mark dates with a vertical line
and h_lines draw reference values.
Missing values (NA) leave a gap in the line.
An interactive SVG line chart.
# A ts object can be passed directly line_chart(AirPassengers, y = "passengers", title = "Airline passengers") # The classic data frame interface still works airpassengers <- data.frame( passengers = as.matrix(AirPassengers), date = zoo::as.Date(time(AirPassengers)) ) line_chart(data = airpassengers, x = "date", y = "passengers") # Several series from an mts object, rebased to 100 at the start of the # visible range: zoom with the range buttons or the navigator and the # comparison is recomputed line_chart( EuStockMarkets, transform = "index", title = "European stock indices", subtitle = "Daily closing prices, rebased to 100" ) # Long data with a group column, area fill and shaded recessions library(ggplot2) # for the economics data set recessions <- data.frame( start = as.Date(c("1969-12-01", "1973-11-01", "1980-01-01", "1981-07-01", "1990-07-01", "2001-03-01", "2007-12-01")), end = as.Date(c("1970-11-01", "1975-03-01", "1980-07-01", "1982-11-01", "1991-03-01", "2001-11-01", "2009-06-01")) ) line_chart( economics, x = "date", y = "unemploy", area = TRUE, bands = recessions, value_format = ",.0f", value_suffix = "k", title = "US unemployment", subtitle = "Thousands of persons, recessions shaded" ) # A forecast with its prediction interval fit <- HoltWinters(log(AirPassengers)) fc <- predict(fit, n.ahead = 24, prediction.interval = TRUE) fc_dates <- zoo::as.Date(time(fc)) passengers <- rbind( data.frame(date = zoo::as.Date(time(AirPassengers)), value = as.numeric(AirPassengers), lo = NA, hi = NA, series = "Observed"), data.frame(date = fc_dates, value = exp(fc[, "fit"]), lo = exp(fc[, "lwr"]), hi = exp(fc[, "upr"]), series = "Forecast") ) line_chart( passengers, x = "date", y = "value", group = "series", lower = "lo", upper = "hi", colors = c(Observed = "#4269d0", Forecast = "#ff725c"), events = c("Forecast starts" = as.Date("1961-01-01")), value_format = ",.0f", title = "Airline passengers: Holt-Winters forecast" )# A ts object can be passed directly line_chart(AirPassengers, y = "passengers", title = "Airline passengers") # The classic data frame interface still works airpassengers <- data.frame( passengers = as.matrix(AirPassengers), date = zoo::as.Date(time(AirPassengers)) ) line_chart(data = airpassengers, x = "date", y = "passengers") # Several series from an mts object, rebased to 100 at the start of the # visible range: zoom with the range buttons or the navigator and the # comparison is recomputed line_chart( EuStockMarkets, transform = "index", title = "European stock indices", subtitle = "Daily closing prices, rebased to 100" ) # Long data with a group column, area fill and shaded recessions library(ggplot2) # for the economics data set recessions <- data.frame( start = as.Date(c("1969-12-01", "1973-11-01", "1980-01-01", "1981-07-01", "1990-07-01", "2001-03-01", "2007-12-01")), end = as.Date(c("1970-11-01", "1975-03-01", "1980-07-01", "1982-11-01", "1991-03-01", "2001-11-01", "2009-06-01")) ) line_chart( economics, x = "date", y = "unemploy", area = TRUE, bands = recessions, value_format = ",.0f", value_suffix = "k", title = "US unemployment", subtitle = "Thousands of persons, recessions shaded" ) # A forecast with its prediction interval fit <- HoltWinters(log(AirPassengers)) fc <- predict(fit, n.ahead = 24, prediction.interval = TRUE) fc_dates <- zoo::as.Date(time(fc)) passengers <- rbind( data.frame(date = zoo::as.Date(time(AirPassengers)), value = as.numeric(AirPassengers), lo = NA, hi = NA, series = "Observed"), data.frame(date = fc_dates, value = exp(fc[, "fit"]), lo = exp(fc[, "lwr"]), hi = exp(fc[, "upr"]), series = "Forecast") ) line_chart( passengers, x = "date", y = "value", group = "series", lower = "lo", upper = "hi", colors = c(Observed = "#4269d0", Forecast = "#ff725c"), events = c("Forecast starts" = as.Date("1961-01-01")), value_format = ",.0f", title = "Airline passengers: Holt-Winters forecast" )
Draws one line per item (a country, a product, a team...) that grows as
time advances, with a moving head at its tip: a dot, the name of the item
and its live value. The axes rescale smoothly as the race goes, the labels
spread so they never overlap, and a ranking emerges. Switch to the rank
mode to watch the same race as a bump chart (rank 1 at the top), keep only
the leaders in colour with top_n, follow a sliding window of the last
periods with window, and annotate key moments with events.
line_race( data, x, y, group, mode = c("value", "rank"), top_n = NULL, fill = NULL, category = NULL, color_category = NULL, highlight = NULL, y_scale = c("linear", "log"), y_zero = TRUE, window = NULL, grow = FALSE, events = NULL, labels = TRUE, stroke_width = 2.5, dot_radius = 4.5, fill_gaps = TRUE, agg = c("sum", "mean", "max", "min", "last"), x_title = NULL, y_title = NULL, frame_dur = 700, ease = "Linear", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", grid_col = "#ececec", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )line_race( data, x, y, group, mode = c("value", "rank"), top_n = NULL, fill = NULL, category = NULL, color_category = NULL, highlight = NULL, y_scale = c("linear", "log"), y_zero = TRUE, window = NULL, grow = FALSE, events = NULL, labels = TRUE, stroke_width = 2.5, dot_radius = 4.5, fill_gaps = TRUE, agg = c("sum", "mean", "max", "min", "last"), x_title = NULL, y_title = NULL, frame_dur = 700, ease = "Linear", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", grid_col = "#ececec", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )
data |
The data frame containing the variables to consider, in long format (one row per line and period). |
x |
The name of the time column: numeric (e.g. years), |
y |
The name of the numeric column holding the values. |
group |
The name of the column identifying the lines (one line per distinct value). |
mode |
What the vertical axis shows: |
top_n |
Optional. A number of lines: only the current top |
fill |
Optional. The colour of the lines: a single colour, a vector
of colours (recycled), or a named vector mapping colours to lines (or to
categories, with |
category |
Optional. The name of a column grouping the lines (e.g. a continent): the lines are coloured by category, with a clickable legend. |
color_category |
Optional. The name of a D3 categorical colour scheme,
such as "Tableau10", "Set2" or "Dark2", used when |
highlight |
Optional. A character vector of lines to pin from the start (they are highlighted, coloured and labelled). |
y_scale |
The scale of the values: |
y_zero |
Logical. Start the value axis at zero (linear scale only).
Defaults to |
window |
Optional. A number of periods: the time axis then slides to
show only the last |
grow |
Logical. Instead of showing the whole time range from the
start, let the time axis grow with the race, so the heads stay near the
right edge. Ignored with |
events |
Optional. Annotations that pop up when the race reaches
them: a named vector whose values are the times and whose names are the
labels (e.g. |
labels |
Logical. Show the name and the live value next to the head
of each line. Defaults to |
stroke_width |
The width of the lines, in pixels. Defaults to 2.5. |
dot_radius |
The radius of the dot at the head of each line, in pixels. Defaults to 4.5. |
fill_gaps |
Logical. Interpolate the values of a line between the
periods where it is known (otherwise the line is broken). Defaults to
|
agg |
How rows with the same line and period are combined:
|
x_title |
Optional. The title of the time axis. |
y_title |
Optional. The title of the value axis, drawn above it.
Defaults to the name of |
frame_dur |
The duration of one period, in milliseconds. Defaults to 700. |
ease |
The easing of the movement within a period, the name of a D3
easing function without its |
autoplay |
Logical. Start playing when the chart scrolls into view.
Defaults to |
loop |
Logical. Start again at the end. Defaults to |
controls |
Logical. Show the player and the mode buttons. Defaults to
|
start_frame |
The period shown first: |
time_format |
Optional. A d3 time format for date periods, e.g.
|
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
grid_col |
The colour of the grid lines. Defaults to "#ececec"; use
|
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
tooltip |
Logical. Show tooltips on hover. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
The data must be in long format: one row per line and period. The time
column can be numeric (years), a Date, a date-time, or a character
or factor column of ordered periods (shown as an ordinal axis, in the
order of the factor levels or in alphabetical order).
An interactive SVG racing line chart (an r2d3 htmlwidget).
The player at the bottom plays and pauses the race, and its timeline can be dragged or clicked to move in time. The speed (0.5x to 4x) and the loop can be changed. With the keyboard: space plays or pauses, the arrows step one period, Home and End jump to the start and the end.
Hover the chart to see a crosshair at the period under the mouse, listing the leading values and ranks at that time; the line closest to the mouse is highlighted and the others are dimmed. The tooltip keeps updating while the race plays.
Hover a label to see a summary of the line (value, rank, change since its first period, peak).
Click a line or a label to pin it: it stays highlighted (and
coloured and labelled, even outside the top_n) until clicked
again. Click an empty area of the chart to clear the pins.
The buttons at the top right switch between values and ranks.
With category, click a legend entry to hide or show a
category, double-click it to isolate it; hovering it highlights its
lines.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a line or a label sets input$id_clicked to a list with
name, category, period, value, rank and
pinned; input$id_frame gives the current period (a list with
its index and label). The time, the speed, the loop, the mode,
the pinned lines and the hidden categories are kept when the chart is
re-rendered.
library(gapminder) # needed for the gapminder data frame library(dplyr) # needed for data wrangling gapminder %>% filter(country %in% c("China", "India", "Japan", "Korea, Rep.", "Indonesia", "Thailand", "Vietnam", "Philippines")) %>% line_race( x = "year", y = "gdpPercap", group = "country", y_scale = "log", value_prefix = "$", value_format = ",.0f", y_title = "GDP per capita (log scale)", title = "The Asian growth race", events = c("Reforms in China" = 1978, "Asian crisis" = 1997) ) # Every country, the ten longest lives in colour; switch to ranks live line_race( gapminder, x = "year", y = "lifeExp", group = "country", category = "continent", top_n = 10, y_zero = FALSE, value_format = ".1f", y_title = "Life expectancy (years)", highlight = "Japan", title = "Life expectancy, 1952 to 2007" ) # Character periods, as a bump chart race sales <- data.frame( quarter = rep(paste0(rep(2022:2023, each = 4), "-Q", 1:4), 4), brand = rep(c("Alpha", "Beta", "Gamma", "Delta"), each = 8), units = c(10, 14, 18, 25, 30, 33, 35, 40, 22, 21, 24, 23, 26, 31, 37, 46, 15, 19, 26, 28, 27, 25, 24, 22, 30, 27, 22, 20, 21, 24, 30, 35) ) line_race(sales, x = "quarter", y = "units", group = "brand", mode = "rank", frame_dur = 900, title = "Units sold per quarter")library(gapminder) # needed for the gapminder data frame library(dplyr) # needed for data wrangling gapminder %>% filter(country %in% c("China", "India", "Japan", "Korea, Rep.", "Indonesia", "Thailand", "Vietnam", "Philippines")) %>% line_race( x = "year", y = "gdpPercap", group = "country", y_scale = "log", value_prefix = "$", value_format = ",.0f", y_title = "GDP per capita (log scale)", title = "The Asian growth race", events = c("Reforms in China" = 1978, "Asian crisis" = 1997) ) # Every country, the ten longest lives in colour; switch to ranks live line_race( gapminder, x = "year", y = "lifeExp", group = "country", category = "continent", top_n = 10, y_zero = FALSE, value_format = ".1f", y_title = "Life expectancy (years)", highlight = "Japan", title = "Life expectancy, 1952 to 2007" ) # Character periods, as a bump chart race sales <- data.frame( quarter = rep(paste0(rep(2022:2023, each = 4), "-Q", 1:4), 4), brand = rep(c("Alpha", "Beta", "Gamma", "Delta"), each = 8), units = c(10, 14, 18, 25, 30, 33, 35, 40, 22, 21, 24, 23, 26, 31, 37, 46, 15, 19, 26, 28, 27, 25, 24, 22, 30, 27, 22, 20, 21, 24, 30, 35) ) line_race(sales, x = "quarter", y = "units", group = "brand", mode = "rank", frame_dur = 900, title = "Units sold per quarter")
A liquid fill gauge represents a single value as a circle filled with an
animated liquid up to the corresponding level. The fill rises smoothly on
load, two wave layers give the water a natural depth, and the label text
changes color at the water surface — appearing in text_color above
the water and in wave_text_color below it.
liquid_chart( value, label = NULL, fill_color = "steelblue", circle_color = NULL, circle_thickness = 0.05, text_color = NULL, wave_text_color = "white", text_size = 0.38, wave_amplitude = 0.09, wave_count = 2, wave_speed = 1, title = NULL, title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", width = NULL, height = NULL )liquid_chart( value, label = NULL, fill_color = "steelblue", circle_color = NULL, circle_thickness = 0.05, text_color = NULL, wave_text_color = "white", text_size = 0.38, wave_amplitude = 0.09, wave_count = 2, wave_speed = 1, title = NULL, title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", width = NULL, height = NULL )
value |
Numeric. The fill level, between 0 and 1 (0 = empty, 1 = full). |
label |
Character. Text displayed in the center of the gauge. Defaults
to |
fill_color |
The color of the liquid. Defaults to |
circle_color |
The color of the outer ring. Defaults to
|
circle_thickness |
Thickness of the outer ring as a fraction of the
circle radius. Defaults to |
text_color |
Color of the label text above the water surface. Defaults
to |
wave_text_color |
Color of the label text below (inside) the water
surface. Defaults to |
text_size |
Font size of the label as a fraction of the circle radius.
Defaults to |
wave_amplitude |
Height of the wave as a fraction of the circle radius.
Defaults to |
wave_count |
Number of full wave cycles visible across the circle.
Defaults to |
wave_speed |
Speed of the horizontal wave animation. Higher values are
faster. Defaults to |
title |
Optional. A label displayed below the circle. |
title_font_size |
Font size of the title in pixels. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An animated SVG liquid fill gauge.
# Basic usage — 55% fill liquid_chart(value = 0.55) # Custom color and label liquid_chart( value = 0.72, label = "72%", fill_color = "#e67e22", title = "Disk usage" ) # Low fill with a raw value label liquid_chart( value = 0.28, label = "28%", fill_color = "tomato", circle_color = "tomato", text_color = "tomato", wave_text_color = "white" )# Basic usage — 55% fill liquid_chart(value = 0.55) # Custom color and label liquid_chart( value = 0.72, label = "72%", fill_color = "#e67e22", title = "Disk usage" ) # Low fill with a raw value label liquid_chart( value = 0.28, label = "28%", fill_color = "tomato", circle_color = "tomato", text_color = "tomato", wave_text_color = "white" )
A lighter alternative to bar_chart(): each value is drawn as
a thin stem ending in a dot. The data can be one row per category, or raw
rows that are aggregated for you (agg); leave y empty to count
rows. With group, each category gets one lollipop per group, side by
side. Lollipops grow in when the chart is drawn, show their values, and can
be re-sorted from the chart itself.
lollipop_chart( data, x, y = NULL, sort = "none", bg_col = "white", x_ticks = NULL, y_ticks = NULL, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, line_stroke = NULL, line_stroke_width = 2, circle_fill = NULL, circle_stroke = NULL, circle_stroke_width = 1.5, circle_radius = 6, axis_col = "#333333", width = NULL, height = NULL, group = NULL, agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9", opacity = 1 )lollipop_chart( data, x, y = NULL, sort = "none", bg_col = "white", x_ticks = NULL, y_ticks = NULL, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, line_stroke = NULL, line_stroke_width = 2, circle_fill = NULL, circle_stroke = NULL, circle_stroke_width = 1.5, circle_radius = 6, axis_col = "#333333", width = NULL, height = NULL, group = NULL, agg = c("sum", "mean", "median", "min", "max", "count"), labels = TRUE, highlight = NULL, ref_lines = NULL, negative_fill = NULL, legend = NULL, controls = TRUE, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9", opacity = 1 )
data |
The data frame containing the variables to consider. |
x |
The name of the categorical variable (one lollipop per value), plotted along the x-axis. |
y |
The name of the numeric variable, plotted along the y-axis. When
|
sort |
The initial order of the lollipops: |
bg_col |
The background color of the SVG. Defaults to "white". |
x_ticks |
Not used; kept for compatibility. |
y_ticks |
Optional. The approximate number of y-axis ticks. |
x_font_size |
The font size of the category labels. Defaults to 11. |
y_font_size |
The font size of the value axis labels. Defaults to 11. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
x_title |
Optional. The title of the category axis. |
x_title_font_size |
The font size of the category axis title. Defaults to 13. |
y_title |
Optional. The title of the value axis, drawn above it.
Defaults to the name of |
y_title_font_size |
The font size of the value axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
line_stroke |
Optional. The colour of the stems. Defaults to the colour of the dots. |
line_stroke_width |
The width of the stems, in pixels. Defaults to 2. |
circle_fill |
The colour of the dots. A single colour, or, without
|
circle_stroke |
Optional. The colour of the ring around the dots. Defaults to the background colour. |
circle_stroke_width |
The width of the ring around the dots. Defaults to 1.5. |
circle_radius |
The radius of the dots, in pixels. Defaults to 6. Dots are made smaller when there is not enough room for them. |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
group |
Optional. The name of a column that splits each category into groups, drawn side by side (one colour per group, with a clickable legend). |
agg |
How rows with the same category (and group) are combined:
|
labels |
Logical. Write the values next to the dots (when every label
fits). Defaults to |
highlight |
Optional. A character vector of categories to emphasise;
the other lollipops are drawn in grey (or faded, with |
ref_lines |
Optional. Numeric values drawn as dashed reference lines across the bars (e.g. a target or an average); names are used as labels. |
negative_fill |
Optional. The colour of negative lollipops (without
|
legend |
Logical. Show the legend. When |
controls |
Logical. Show the sort buttons. Defaults to |
tooltip |
Logical. Show a tooltip on hover. Defaults to |
animate |
Logical. Animate the lollipops when the chart is first
drawn. Defaults to |
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
grid_col |
The colour of the grid lines. Defaults to "#e9e9e9"; use
|
opacity |
The opacity of the lollipops (from 0 to 1). Defaults to 1. |
An interactive SVG lollipop chart (an r2d3 htmlwidget).
Hover a lollipop to see its value, its share of the total and its
rank; with group, the tooltip lists every group for that
category.
The buttons at the top right switch between the original order, largest first and smallest first.
Click a legend entry to hide or show a group, double-click it to isolate it. Hovering a legend entry highlights the group.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a lollipop sets input$id_clicked to a list with the
category and group of the lollipop. The sort order and the
hidden groups are kept when the chart is re-rendered.
library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for data wrangling mpg %>% group_by(drv) %>% summarise(median_cty = median(cty)) %>% lollipop_chart( x = "drv", y = "median_cty", sort = "ascending", x_title = "drv variable", y_title = "median cty", title = "Median cty per drv" ) # Aggregate raw rows directly, and highlight two categories lollipop_chart( mpg, x = "manufacturer", y = "hwy", agg = "median", sort = "descending", highlight = c("honda", "toyota"), title = "Median highway miles per gallon" ) # One lollipop per group lollipop_chart( mpg, x = "class", y = "cty", group = "year", agg = "mean", value_format = ".1f", title = "City miles per gallon, 1999 and 2008" )library(ggplot2) # needed for the mpg data frame library(dplyr) # needed for data wrangling mpg %>% group_by(drv) %>% summarise(median_cty = median(cty)) %>% lollipop_chart( x = "drv", y = "median_cty", sort = "ascending", x_title = "drv variable", y_title = "median cty", title = "Median cty per drv" ) # Aggregate raw rows directly, and highlight two categories lollipop_chart( mpg, x = "manufacturer", y = "hwy", agg = "median", sort = "descending", highlight = c("honda", "toyota"), title = "Median highway miles per gallon" ) # One lollipop per group lollipop_chart( mpg, x = "class", y = "cty", group = "year", agg = "mean", value_format = ".1f", title = "City miles per gallon, 1999 and 2008" )
A mosaic chart, also called a Marimekko or Mekko chart, shows how two
categorical variables relate to each other and to the whole. Each column
stands for one category of x, and its width is that category's share
of the grand total. Each column is then split into stacked segments, one per
category of fill, normalised to 100% of the column. So the area of
every cell is proportional to its count (or summed value), and you can read
both marginal and conditional shares in a single picture. The look follows
the mosaic example from the Vega-Lite gallery: white gaps between cells,
percentage axes, column labels across the top and in-cell labels wherever
they fit.
Hovering a cell highlights it and shows a tooltip with its count, the share
of its column in the total and its share within the column. Hovering a
legend entry highlights every cell of that fill category, and
hovering a column label highlights the whole column.
Column and segment order follow the factor levels of x and
fill. Character columns are ordered alphabetically and numeric
columns in increasing order.
mosaic_chart( data, x, fill, value = NULL, colors = NULL, gap = 2, label_type = c("percent", "count", "both", "none"), value_format = ",.0f", label_font_size = 11, label_col = NULL, column_font_size = 12, hover = TRUE, animate = TRUE, legend = TRUE, legend_title = NULL, legend_font_size = 11, x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 10, y_font_size = 10, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )mosaic_chart( data, x, fill, value = NULL, colors = NULL, gap = 2, label_type = c("percent", "count", "both", "none"), value_format = ",.0f", label_font_size = 11, label_col = NULL, column_font_size = 12, hover = TRUE, animate = TRUE, legend = TRUE, legend_title = NULL, legend_font_size = 11, x_title = NULL, y_title = NULL, axis_title_font_size = 12, x_font_size = 10, y_font_size = 10, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
x |
The name of the categorical column that defines the columns. The width of each column is its share of the total. |
fill |
The name of the categorical column that splits each column into stacked segments, normalised to 100% within the column. |
value |
Optional. The name of a numeric (non-negative) column that is
summed for each |
colors |
Optional. A vector of colors, one per |
gap |
Width in pixels of the white gaps between columns and between
segments. Defaults to |
label_type |
What to print inside each cell when there is room for it:
|
value_format |
A d3-format specifier used to display counts or values
in the labels and the tooltip (e.g. |
label_font_size |
Font size of the in-cell labels. Defaults to
|
label_col |
Optional. Color of the in-cell labels. Defaults to
|
column_font_size |
Font size of the column ( |
hover |
Whether to highlight the hovered cell and show a tooltip.
Defaults to |
animate |
Whether the columns grow into place with a short staggered
animation on first render. Defaults to |
legend |
Whether to display a legend of the |
legend_title |
Optional. Title of the legend. Defaults to |
legend_font_size |
Font size of the legend text. Defaults to |
x_title |
Optional. Title of the x-axis (bottom). |
y_title |
Optional. Title of the y-axis (left). |
axis_title_font_size |
Font size of the axis titles. Defaults to
|
x_font_size |
Font size of the x-axis tick labels. Defaults to
|
y_font_size |
Font size of the y-axis tick labels. Defaults to
|
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. It is also the color of the gaps
between cells. Defaults to |
axis_col |
Color of the axes, the axis labels, the column labels, the
legend text and the title. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG mosaic chart.
# Survival on the Titanic by passenger class (pre-aggregated counts) titanic <- as.data.frame(Titanic) mosaic_chart( data = titanic, x = "Class", fill = "Survived", value = "Freq", colors = c("#e45756", "#4c78a8"), x_title = "Share of passengers and crew", y_title = "Share within class", title = "Who survived the Titanic?" ) # Counting rows: gears by number of cylinders. Factor levels set the order # of both the columns and the stacked segments. cars <- mtcars cars$cyl <- factor(cars$cyl, levels = c(8, 6, 4), labels = c("8 cyl", "6 cyl", "4 cyl")) cars$gear <- factor(cars$gear, levels = c(3, 4, 5), labels = c("3 gears", "4 gears", "5 gears")) mosaic_chart( data = cars, x = "cyl", fill = "gear", label_type = "both", legend_title = "Gears", title = "Motor Trend cars: gears by cylinders" ) # Hair and eye color of statistics students (counts are summed over Sex) hair_eye <- as.data.frame(HairEyeColor) hair_eye$Eye <- factor(hair_eye$Eye, levels = c("Brown", "Hazel", "Green", "Blue")) mosaic_chart( data = hair_eye, x = "Hair", fill = "Eye", value = "Freq", colors = c("#8c564b", "#bcbd22", "#2ca02c", "#1f77b4"), gap = 3, x_title = "Hair color", title = "Hair and eye color of 592 students" )# Survival on the Titanic by passenger class (pre-aggregated counts) titanic <- as.data.frame(Titanic) mosaic_chart( data = titanic, x = "Class", fill = "Survived", value = "Freq", colors = c("#e45756", "#4c78a8"), x_title = "Share of passengers and crew", y_title = "Share within class", title = "Who survived the Titanic?" ) # Counting rows: gears by number of cylinders. Factor levels set the order # of both the columns and the stacked segments. cars <- mtcars cars$cyl <- factor(cars$cyl, levels = c(8, 6, 4), labels = c("8 cyl", "6 cyl", "4 cyl")) cars$gear <- factor(cars$gear, levels = c(3, 4, 5), labels = c("3 gears", "4 gears", "5 gears")) mosaic_chart( data = cars, x = "cyl", fill = "gear", label_type = "both", legend_title = "Gears", title = "Motor Trend cars: gears by cylinders" ) # Hair and eye color of statistics students (counts are summed over Sex) hair_eye <- as.data.frame(HairEyeColor) hair_eye$Eye <- factor(hair_eye$Eye, levels = c("Brown", "Hazel", "Green", "Blue")) mosaic_chart( data = hair_eye, x = "Hair", fill = "Eye", value = "Freq", colors = c("#8c564b", "#bcbd22", "#2ca02c", "#1f77b4"), gap = 3, x_title = "Hair color", title = "Hair and eye color of 592 students" )
Draws a sailor flexing both arms whose biceps grow with a level between 0 and 1: flat, skinny arms at 0 and giant biceps at 1. The sailor strains at low levels (squeezed eyes, gritted teeth, a red face and drops of sweat) and grins at high ones; the shoulders widen, the tattoos stretch, veins show and the biggest biceps sparkle. When the chart scrolls into view, the biceps grow from flat to the level while the percentage above the portrait counts up and the current stage ("Noodle arms", "Twigs", "Toned", "Strong", "Buff", "Mighty") is written under it.
muscle_growth( fill_level = 0.5, skin_color = "#e8b48f", hair_color = "#3b2a20", shirt_color = "#2a62b8", panel_color = "#d9ecf7", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Muscle growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, tattoos = TRUE, sparkles = TRUE, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )muscle_growth( fill_level = 0.5, skin_color = "#e8b48f", hair_color = "#3b2a20", shirt_color = "#2a62b8", panel_color = "#d9ecf7", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Muscle growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, tattoos = TRUE, sparkles = TRUE, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )
fill_level |
A number between 0 and 1: how big the biceps are (values outside are clamped). 0 is flat and 1 is giant. Defaults to 0.5. |
skin_color |
The colour of the skin. Defaults to "#e8b48f". |
hair_color |
The colour of the moustache, the eyebrows and the sideburns. Defaults to "#3b2a20". |
shirt_color |
The colour of the stripes of the tank top. Defaults to "#2a62b8". |
panel_color |
The colour of the card behind the portrait. Defaults to
"#d9ecf7"; use |
render_fill_label |
Logical. Show the percentage and the stage above the portrait. Defaults to TRUE. |
label_color |
The colour of the percentage, the stage, the target and the speech bubble. Defaults to "#333". |
label_font_size |
Optional. The font size of the percentage, a number or a CSS size such as "16px". By default it grows with the chart. |
title_text |
Optional. A caption below the portrait. Defaults to
"Muscle growth"; use |
title_color |
The colour of the caption. Defaults to "#333". |
title_font_size |
The font size of the caption, a number or a CSS size such as "14px". Defaults to 14. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
target |
Optional. A level between 0 and 1, drawn as a dashed outline of the biceps at that size and written in the top right corner. |
tattoos |
Logical. Draw an anchor and a heart tattoo on the arms; they stretch as the biceps grow. Defaults to TRUE. |
sparkles |
Logical. Let the biggest biceps (above 85 percent) sparkle. Defaults to TRUE. |
sway |
Logical. Let the sailor breathe and blink, the weak arms tremble and the sea move. Defaults to TRUE. |
draggable |
Logical. Let the viewer change the level by dragging or with the arrow keys. Defaults to FALSE. |
animate |
Logical. Grow the biceps from flat when the chart first comes into view. Defaults to TRUE. |
bg_col |
The background colour. Defaults to "white". |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
An r2d3 htmlwidget.
Move the mouse across the chart: the eyes follow it.
Hover the portrait: the biceps twitch.
Click the portrait: the sailor flexes harder, the cap jumps and a speech bubble pops up.
With draggable = TRUE, drag up to grow the biceps and down to
shrink them, or focus the chart (click it or press Tab) and use the
arrow keys (1 percent per press, 10 with Shift).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking the portrait sets input$id_clicked to a list with
value and stage, and, with draggable = TRUE, setting a
level sets input$id_value to the new level (a number between 0 and
1). When the chart is re-rendered with a new level, the biceps grow or
shrink from the old size to the new one.
muscle_growth(fill_level = 1) muscle_growth(0.3, target = 0.75, title_text = "Training plan completed") muscle_growth( fill_level = 0.6, skin_color = "#8d5a3b", hair_color = "#1f1a17", shirt_color = "#c0392b", panel_color = "#fdf1e3", draggable = TRUE, title_text = "Drag up to pump the biceps" )muscle_growth(fill_level = 1) muscle_growth(0.3, target = 0.75, title_text = "Training plan completed") muscle_growth( fill_level = 0.6, skin_color = "#8d5a3b", hair_color = "#1f1a17", shirt_color = "#c0392b", panel_color = "#fdf1e3", draggable = TRUE, title_text = "Drag up to pump the biceps" )
Draws a network (a graph) with a force-directed layout: nodes repel each other while the links pull connected nodes together, so that clusters appear on their own. The nodes can be coloured by group and sized by a value (by default by their number of links).
network_graph( data, from, to, weight = NULL, nodes = NULL, node_id = NULL, node_group = NULL, node_size = NULL, node_label = NULL, directed = FALSE, colors = NULL, node_radius = c(5, 18), link_col = "#a7b0ba", show_labels = NULL, label_font_size = 10, charge = -160, link_distance = NULL, zoom = TRUE, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )network_graph( data, from, to, weight = NULL, nodes = NULL, node_id = NULL, node_group = NULL, node_size = NULL, node_label = NULL, directed = FALSE, colors = NULL, node_radius = c(5, 18), link_col = "#a7b0ba", show_labels = NULL, label_font_size = 10, charge = -160, link_distance = NULL, zoom = TRUE, legend = TRUE, legend_font_size = 11, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
A data frame of links, one row per link. |
from, to
|
The names of the columns giving the two ends of each link. |
weight |
Optional. The name of a numeric column giving the strength of each link (drawn as its width). |
nodes |
Optional. A data frame of nodes, to give them a group, a size or a label (nodes that only appear here are drawn without links). |
node_id |
The name of the column of |
node_group, node_size, node_label
|
Optional. Names of columns of
|
directed |
Logical. Draw arrows from |
colors |
Optional. Colours of the groups: one per group or a named vector matched to the groups. |
node_radius |
The smallest and the largest node radius in pixels.
Defaults to |
link_col |
The colour of the links. Defaults to "#a7b0ba". |
show_labels |
Logical. Write the labels next to the nodes. By default every label is shown for networks of up to 40 nodes, otherwise only the labels of the biggest nodes; hovering a node always shows the labels of its neighbours. |
label_font_size |
The font size of the labels. Defaults to 10. |
charge |
How strongly the nodes repel each other (a negative number). Defaults to -160. |
link_distance |
Optional. The preferred length of the links in pixels. By default it grows with the size of the chart and shrinks with the number of nodes. |
zoom |
Logical. Let the viewer zoom and pan. Defaults to TRUE. |
legend |
Logical. Show a legend of the groups. Defaults to TRUE. |
legend_font_size |
The font size of the legend. Defaults to 11. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Let the network settle into place when the chart is drawn (otherwise it is drawn already settled). Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text. Defaults to "#333333". |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a node to highlight its neighbours and see its details; drag a node to
move it (the network follows); scroll to zoom and drag the background to
pan (zoom). Click a group in the legend to highlight it. The network
settles into place when the chart is drawn. Inside Shiny, clicking a node
sets input$<id>_clicked to a list with id, label,
group and degree.
# Who works with whom in a small company team <- data.frame( from = c("Ana", "Ana", "Ana", "Ben", "Ben", "Chloe", "Chloe", "Dev", "Eve", "Eve", "Farid", "Gus", "Gus", "Hana", "Hana", "Ivo", "Jo", "Jo", "Kim", "Ana", "Eve"), to = c("Ben", "Chloe", "Dev", "Chloe", "Dev", "Dev", "Eve", "Eve", "Farid", "Gus", "Gus", "Hana", "Ivo", "Ivo", "Jo", "Jo", "Kim", "Lea", "Lea", "Hana", "Kim") ) people <- data.frame( name = c("Ana", "Ben", "Chloe", "Dev", "Eve", "Farid", "Gus", "Hana", "Ivo", "Jo", "Kim", "Lea"), team = rep(c("Product", "Engineering", "Sales"), each = 4) ) network_graph(team, from = "from", to = "to", nodes = people, node_group = "team", title = "Who works with whom") # A directed network: which manufacturers make which classes of cars mpg <- ggplot2::mpg pairs <- unique(mpg[, c("manufacturer", "class")]) network_graph(as.data.frame(pairs), from = "manufacturer", to = "class", directed = TRUE, charge = -220)# Who works with whom in a small company team <- data.frame( from = c("Ana", "Ana", "Ana", "Ben", "Ben", "Chloe", "Chloe", "Dev", "Eve", "Eve", "Farid", "Gus", "Gus", "Hana", "Hana", "Ivo", "Jo", "Jo", "Kim", "Ana", "Eve"), to = c("Ben", "Chloe", "Dev", "Chloe", "Dev", "Dev", "Eve", "Eve", "Farid", "Gus", "Gus", "Hana", "Ivo", "Ivo", "Jo", "Jo", "Kim", "Lea", "Lea", "Hana", "Kim") ) people <- data.frame( name = c("Ana", "Ben", "Chloe", "Dev", "Eve", "Farid", "Gus", "Hana", "Ivo", "Jo", "Kim", "Lea"), team = rep(c("Product", "Engineering", "Sales"), each = 4) ) network_graph(team, from = "from", to = "to", nodes = people, node_group = "team", title = "Who works with whom") # A directed network: which manufacturers make which classes of cars mpg <- ggplot2::mpg pairs <- unique(mpg[, c("manufacturer", "class")]) network_graph(as.data.frame(pairs), from = "manufacturer", to = "class", directed = TRUE, charge = -220)
Draws a person in profile whose nose grows with a level between 0 and 1, like the nose of a teller of tall tales: a small nose at 0 and a nose that reaches across the chart at 1. A twig with leaves sprouts from a long nose and a bird lands on the longest one, while the person looks more and more nervous (a wavy mouth, raised brows, a blush and a drop of sweat). When the chart scrolls into view, the nose grows from its smallest size to the level while the percentage above the portrait counts up and the current stage ("Honest", "Little fib", "White lie", "Tall tale", "Whopper", "Pants on fire") is written under it.
nose_growth( fill_level = 0.5, skin_color = "#f3c9a8", hair_color = "#c0622f", shirt_color = "#27365c", panel_color = "#e3f1ea", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Nose growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, leaves = TRUE, bird = TRUE, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )nose_growth( fill_level = 0.5, skin_color = "#f3c9a8", hair_color = "#c0622f", shirt_color = "#27365c", panel_color = "#e3f1ea", render_fill_label = TRUE, label_color = "#333", label_font_size = NULL, title_text = "Nose growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", target = NULL, leaves = TRUE, bird = TRUE, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )
fill_level |
A number between 0 and 1: how long the nose is (values outside are clamped). Defaults to 0.5. |
skin_color |
The colour of the skin. Defaults to "#f3c9a8". |
hair_color |
The colour of the hair and the eyebrow. Defaults to "#c0622f". |
shirt_color |
The colour of the stripes of the top. Defaults to "#27365c". |
panel_color |
The colour of the card behind the portrait. Defaults to
"#e3f1ea"; use |
render_fill_label |
Logical. Show the percentage and the stage above the portrait. Defaults to TRUE. |
label_color |
The colour of the percentage, the stage, the target and the speech bubble. Defaults to "#333". |
label_font_size |
Optional. The font size of the percentage, a number or a CSS size such as "16px". By default it grows with the chart. |
title_text |
Optional. A caption below the portrait. Defaults to "Nose
growth"; use |
title_color |
The colour of the caption. Defaults to "#333". |
title_font_size |
The font size of the caption, a number or a CSS size such as "14px". Defaults to 14. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
target |
Optional. A level between 0 and 1, drawn as a dashed outline of the nose at that length, with a label above its tip. |
leaves |
Logical. Let a twig with leaves sprout from the nose above 62 percent. Defaults to TRUE. |
bird |
Logical. Let a bird land on the nose above 92 percent. Defaults to TRUE. |
sway |
Logical. Let the ponytail, the twig and the bird move gently and the person breathe and blink. Defaults to TRUE. |
draggable |
Logical. Let the viewer change the level by dragging or with the arrow keys. Defaults to FALSE. |
animate |
Logical. Grow the nose when the chart first comes into view. Defaults to TRUE. |
bg_col |
The background colour. Defaults to "white". |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
An r2d3 htmlwidget.
Move the mouse across the chart: the eye follows it.
Hover the portrait: the nose twitches.
Click the portrait: the nose wobbles, the ponytail swings, the bird hops and the person protests in a speech bubble.
With draggable = TRUE, drag right to grow the nose and left
to shrink it (the tip follows the mouse), or focus the chart (click it
or press Tab) and use the arrow keys (1 percent per press, 10 with
Shift).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking the portrait sets input$id_clicked to a list with
value and stage, and, with draggable = TRUE, setting a
level sets input$id_value to the new level (a number between 0 and
1). When the chart is re-rendered with a new level, the nose grows or
shrinks from the old length to the new one.
nose_growth(fill_level = 1) nose_growth(0.3, target = 0.7, title_text = "Claims not yet fact-checked") nose_growth( fill_level = 0.55, skin_color = "#8d5a3b", hair_color = "#1f1a17", shirt_color = "#c0392b", panel_color = "#fdf1e3", draggable = TRUE, title_text = "Drag the nose" )nose_growth(fill_level = 1) nose_growth(0.3, target = 0.7, title_text = "Claims not yet fact-checked") nose_growth( fill_level = 0.55, skin_color = "#8d5a3b", hair_color = "#1f1a17", shirt_color = "#c0392b", panel_color = "#fdf1e3", draggable = TRUE, title_text = "Drag the nose" )
Draws the seats of an assembly as a hemicycle: one dot per seat, the
parties forming wedges from left to right in the order of the data (or by
size, see sort). A dashed line marks the majority, and the centre
shows the total number of seats. Rows with the same party are added up.
parliament_chart( data, categorical_column, numerical_column, seat_size = NULL, padding = NULL, max_rows = NULL, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", width = NULL, height = NULL, subtitle = NULL, subtitle_font_size = 13, fill = NULL, color_category = NULL, previous = NULL, majority = TRUE, coalition = NULL, coalition_builder = TRUE, regroup = TRUE, sort = c("none", "descending", "ascending"), arc = 180, inner_radius = 0.4, seat_shape = c("circle", "square"), center_label = "seats", legend = TRUE, tooltip = TRUE, animate = TRUE, axis_col = "#333333" )parliament_chart( data, categorical_column, numerical_column, seat_size = NULL, padding = NULL, max_rows = NULL, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", width = NULL, height = NULL, subtitle = NULL, subtitle_font_size = 13, fill = NULL, color_category = NULL, previous = NULL, majority = TRUE, coalition = NULL, coalition_builder = TRUE, regroup = TRUE, sort = c("none", "descending", "ascending"), arc = 180, inner_radius = 0.4, seat_shape = c("circle", "square"), center_label = "seats", legend = TRUE, tooltip = TRUE, animate = TRUE, axis_col = "#333333" )
data |
A data frame with one row per party (rows with the same party are added up). |
categorical_column |
The name of the column giving the parties. |
numerical_column |
The name of the column giving the number of seats (whole numbers; other numbers are rounded with a warning). |
seat_size |
Optional. The diameter of the seats in pixels. By default the seats are as large as the chart allows. When the seats do not fit, they are made smaller. |
padding |
Optional. The space between two seats, in pixels. By default a fifth of the space given to each seat. |
max_rows |
Optional. The number of rows of seats. By default the number of rows that gives the largest seats. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 20. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
subtitle |
Optional. A subtitle under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
fill |
Optional. The colours of the parties: one colour per party
(recycled, in the order of the data), or a named vector mapping colours
to parties (for instance |
color_category |
Optional. The name of a D3 categorical colour scheme,
such as "Tableau10" or "Set2", used when |
previous |
Optional. The name of a column giving the seats of each party at the previous election: the gains and losses are then shown in the legend and the tooltips. |
majority |
The seats needed for a majority: |
coalition |
Optional. A character vector of parties that form the coalition when the chart is first drawn. |
coalition_builder |
Logical. Let the viewer build a coalition by
clicking parties, with a gauge under the hemicycle. Defaults to
|
regroup |
Logical. Move the seats of the coalition to the left of the
hemicycle. Defaults to |
sort |
The order of the parties from left to right: |
arc |
The angle covered by the seats, in degrees, from 180 (default, a hemicycle) to 360 (a full ring). |
inner_radius |
The radius of the empty centre, as a fraction of the outer radius. Defaults to 0.4. |
seat_shape |
The shape of the seats: |
center_label |
The text under the number of seats in the centre.
Defaults to "seats"; |
legend |
Logical. Show the legend, with the seats and shares (on the
right when there is room, otherwise below). Defaults to |
tooltip |
Logical. Show a tooltip when hovering the seats. Defaults
to |
animate |
Logical. Fill the seats from left to right when the chart
comes into view. Defaults to |
axis_col |
The colour of the texts. Defaults to "#333333". |
The chart is also a coalition builder: click parties to put them together. Their seats gather on the left of the hemicycle, so the coalition has a majority when its seats cross the majority line, and a gauge under the hemicycle counts its seats.
An interactive parliament chart (an r2d3 htmlwidget).
Hover a seat or a legend entry to highlight the party and see its
seats, its share, its rank and how far it is from a majority (and its
gains or losses with previous).
Click a seat or a legend entry (or press Enter on a focused legend
entry) to add the party to the coalition, or to take it out. The
coalition seats move to the left (see regroup), the gauge shows
whether they reach the majority, and "Clear" empties the coalition.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a party sets input$id_clicked to its name, and every change
of the coalition sets input$id_coalition to a list with
parties (a list of names: use unlist() to get a vector),
seats, majority (the seats needed) and hasMajority.
The coalition is kept when the chart is re-rendered (and
input$id_coalition is updated if its seats changed), and the seats
move smoothly to their new places when the results change.
political_results_example <- data.frame( political_party = c("SDP", "CDU", "Linke"), number_of_seats = c(200, 40, 30) ) parliament_chart( data = political_results_example, categorical_column = "political_party", numerical_column = "number_of_seats", title = "An assembly of 270 seats" ) # A toy assembly with party colours, the previous results and a coalition assembly <- data.frame( party = c("Left", "Greens", "Social Democrats", "Liberals", "Conservatives", "Nationalists"), seats = c(28, 41, 152, 63, 187, 79), seats_before = c(39, 30, 171, 48, 170, 92) ) parliament_chart( assembly, "party", "seats", previous = "seats_before", fill = c("#c0392b", "#3ca951", "#ff725c", "#efb118", "#4269d0", "#6b4e9c"), coalition = c("Social Democrats", "Greens", "Liberals"), title = "Who can govern?", subtitle = "Click the parties to build a coalition" )political_results_example <- data.frame( political_party = c("SDP", "CDU", "Linke"), number_of_seats = c(200, 40, 30) ) parliament_chart( data = political_results_example, categorical_column = "political_party", numerical_column = "number_of_seats", title = "An assembly of 270 seats" ) # A toy assembly with party colours, the previous results and a coalition assembly <- data.frame( party = c("Left", "Greens", "Social Democrats", "Liberals", "Conservatives", "Nationalists"), seats = c(28, 41, 152, 63, 187, 79), seats_before = c(39, 30, 171, 48, 170, 92) ) parliament_chart( assembly, "party", "seats", previous = "seats_before", fill = c("#c0392b", "#3ca951", "#ff725c", "#efb118", "#4269d0", "#6b4e9c"), coalition = c("Social Democrats", "Greens", "Liberals"), title = "Who can govern?", subtitle = "Click the parties to build a coalition" )
Draws one slice per category, with its share of the total written on the
slice or next to it. Rows with the same label are added up, and the value
can be left empty to count rows. Small slices can be combined into an
"Other" slice. Set inner_radius to draw a donut chart, whose centre
shows the total, or the hovered slice.
pie_chart( data, value = NULL, label, color_category = NULL, inner_radius = 0, outer_radius = "auto", pad_radius = NULL, pad_angle = NULL, corner_radius = 0, label_font = NULL, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 1, label_height = NULL, width = NULL, height = NULL, fill = NULL, sort = c("descending", "ascending", "none"), max_slices = NULL, other_label = "Other", labels = NULL, label_position = c("auto", "inside", "outside"), legend = TRUE, center_label = NULL, highlight = NULL, start_angle = 0, end_angle = 360, stroke = NULL, stroke_width = NULL, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, axis_col = "#333333" )pie_chart( data, value = NULL, label, color_category = NULL, inner_radius = 0, outer_radius = "auto", pad_radius = NULL, pad_angle = NULL, corner_radius = 0, label_font = NULL, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 1, label_height = NULL, width = NULL, height = NULL, fill = NULL, sort = c("descending", "ascending", "none"), max_slices = NULL, other_label = "Other", labels = NULL, label_position = c("auto", "inside", "outside"), legend = TRUE, center_label = NULL, highlight = NULL, start_angle = 0, end_angle = 360, stroke = NULL, stroke_width = NULL, tooltip = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", subtitle = NULL, subtitle_font_size = 13, axis_col = "#333333" )
data |
The data frame to consider. |
value |
The name of the numeric variable (the size of the slices).
When |
label |
The name of the labelling variable (one slice per value). |
color_category |
Optional. The name of a D3 categorical colour scheme,
such as "Tableau10", "Set2" or "Paired" (see
<https://github.com/d3/d3-scale-chromatic#categorical>), used when
|
inner_radius |
The inner radius, for a donut chart: a number below 1 is a fraction of the outer radius (e.g. 0.6), a larger number is a radius in pixels. Defaults to 0 (a pie). |
outer_radius |
The outer radius in pixels, or "auto" (default) to fill the space available. |
pad_radius |
Optional. From the D3 documentation, the pad radius computes the fixed linear distance separating adjacent arcs, defined as pad_radius * pad_angle. Defaults to the D3 default. |
pad_angle |
Optional. The padding angle between consecutive slices, in radians (e.g. 0.02). |
corner_radius |
The radius of the rounded slice corners, in pixels. Defaults to 0. |
label_font |
Optional. The font family of the legend. Defaults to
|
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
opacity |
The opacity of the slices (from 0 to 1). Defaults to 1. |
label_height |
Optional. The font size of the legend, in pixels. Defaults to 12. |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
fill |
Optional. The colours of the slices: one colour per slice, in the order of the slices (recycled), or a named vector mapping colours to labels. |
sort |
The order of the slices, clockwise from the top:
|
max_slices |
Optional. The maximum number of slices: the smallest
categories are combined into an "Other" slice so that at most
|
other_label |
The label of the combined slice. Defaults to "Other". |
labels |
What to write for each slice: any of |
label_position |
Where the slice labels go: |
legend |
Logical. Show the legend (on the right when there is room,
otherwise below). Defaults to |
center_label |
For a donut chart, the text shown under the total in
the centre: |
highlight |
Optional. A character vector of labels whose slices are pulled out. |
start_angle, end_angle
|
The angles where the pie starts and ends, in degrees, clockwise from the top. Defaults to 0 and 360; use -90 and 90 for a half donut. |
stroke |
The colour of the lines between the slices. Defaults to the background colour. |
stroke_width |
The width of the lines between the slices. Defaults to
1.5 (0 when |
tooltip |
Logical. Show a tooltip when hovering the slices. Defaults
to |
animate |
Logical. Sweep the slices in when the chart is first drawn.
Defaults to |
value_format |
Optional. A D3 format string for the values, such as
|
value_prefix, value_suffix
|
Optional. Text added before and after the
values, such as |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
axis_col |
The colour of the texts. Defaults to "#333333". |
An interactive SVG pie chart (an r2d3 htmlwidget).
Hover a slice (or its legend entry) to pull it out and see its value, its share of the total and its rank; the "Other" slice lists the categories it contains.
Click a legend entry to hide or show a slice (the shares are then computed without it), double-click it to keep only that slice.
Click a slice to pull it out, click it again to put it back.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a slice sets input$id_clicked to its label. The hidden
slices are kept when the chart is re-rendered.
library(ggplot2) # needed for the mpg data frame # Rows are counted when there is no value pie_chart(mpg, label = "class", title = "Cars by class") # A donut chart with the total in the centre energy <- data.frame( source = c("Nuclear", "Hydro", "Wind", "Solar", "Gas", "Coal", "Other"), twh = c(320, 58, 49, 23, 34, 3, 8) ) pie_chart( energy, value = "twh", label = "source", inner_radius = 0.6, center_label = "TWh", title = "Electricity generation by source" ) # A half donut with the small slices combined pie_chart( energy, value = "twh", label = "source", inner_radius = 0.55, start_angle = -90, end_angle = 90, max_slices = 4, legend = FALSE )library(ggplot2) # needed for the mpg data frame # Rows are counted when there is no value pie_chart(mpg, label = "class", title = "Cars by class") # A donut chart with the total in the centre energy <- data.frame( source = c("Nuclear", "Hydro", "Wind", "Solar", "Gas", "Coal", "Other"), twh = c(320, 58, 49, 23, 34, 3, 8) ) pie_chart( energy, value = "twh", label = "source", inner_radius = 0.6, center_label = "TWh", title = "Electricity generation by source" ) # A half donut with the small slices combined pie_chart( energy, value = "twh", label = "source", inner_radius = 0.55, start_angle = -90, end_angle = 90, max_slices = 4, legend = FALSE )
Draws a potted plant whose growth follows a level between 0 and 1. The plant goes through stages: a seed, a sprout, a stem with leaves, a bud (from 55 percent) and a flower that opens fully at 100 percent. It sways gently in the breeze. When the chart scrolls into view, the plant grows from the seed to the level while the percentage counts up and the stage is written below it.
plant_growth( fill_level = 0.5, pot_width = NULL, pot_height = NULL, plant_max_height = NULL, stem_color = "#3ca951", pot_color = "#c96f45", flower_color = "#ff8ab7", stroke_color = NULL, stroke_width = 1.5, render_fill_label = TRUE, title_text = "Plant growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", label_color = "#333", label_font_size = NULL, soil_color = "#5b3a29", target = NULL, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )plant_growth( fill_level = 0.5, pot_width = NULL, pot_height = NULL, plant_max_height = NULL, stem_color = "#3ca951", pot_color = "#c96f45", flower_color = "#ff8ab7", stroke_color = NULL, stroke_width = 1.5, render_fill_label = TRUE, title_text = "Plant growth", title_color = "#333", title_font_size = 14, font = "Verdana, Geneva, Tahoma, sans-serif", label_color = "#333", label_font_size = NULL, soil_color = "#5b3a29", target = NULL, sway = TRUE, draggable = FALSE, animate = TRUE, bg_col = "white", width = NULL, height = NULL )
fill_level |
A number between 0 and 1: how grown the plant is (values outside are clamped). Defaults to 0.5. |
pot_width |
Optional. The width of the pot in pixels. By default it depends on the size of the chart. |
pot_height |
Optional. The height of the pot in pixels. |
plant_max_height |
Optional. The height of the fully grown plant (above the soil) in pixels. By default the plant uses the height available. |
stem_color |
The colour of the stem and the leaves. Defaults to "#3ca951". |
pot_color |
The colour of the pot. Defaults to "#c96f45". |
flower_color |
The colour of the petals of the bud and the flower. Defaults to "#ff8ab7". |
stroke_color |
Optional. The outline colour of the pot. Defaults to a
darker shade of |
stroke_width |
The outline width of the pot. Defaults to 1.5. |
render_fill_label |
Logical. Show the percentage and the stage above the plant. Defaults to TRUE. |
title_text |
Optional. A caption below the pot. Defaults to "Plant
growth"; use |
title_color |
The colour of the caption. Defaults to "#333". |
title_font_size |
The font size of the caption, a number or a CSS size such as "14px". Defaults to 14. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
label_color |
The colour of the percentage and the target label. Defaults to "#333". |
label_font_size |
Optional. The font size of the percentage, a number or a CSS size such as "16px". By default it depends on the size of the chart. |
soil_color |
The colour of the soil. Defaults to "#5b3a29". |
target |
Optional. A level between 0 and 1 marked with a dashed line at the corresponding height. |
sway |
Logical. Let the plant sway in the breeze. Defaults to TRUE. |
draggable |
Logical. Let the viewer change the level by dragging or with the arrow keys. Defaults to FALSE. |
animate |
Logical. Grow the plant from the seed when it first comes into view. Defaults to TRUE. |
bg_col |
The background colour. Defaults to "white". |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
An r2d3 htmlwidget.
Hover the plant: the breeze picks up and the leaves flutter.
Click the plant: a watering can waters it and the plant perks up.
With draggable = TRUE, drag up or down on the plant to set
the level, or focus the chart (click it or press Tab) and use the arrow
keys (1 percent per press, 10 with Shift).
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking the plant sets input$id_clicked to a list with
value and stage, and, with draggable = TRUE, setting a
level sets input$id_value to the new level (a number between 0 and
1). When the chart is re-rendered with a new level, the plant grows (or
shrinks) from the old level to the new one.
plant_growth(0.4) plant_growth(1, title_text = "Project completed") plant_growth( 0.7, target = 0.9, pot_color = "#4269d0", flower_color = "#efb118", draggable = TRUE )plant_growth(0.4) plant_growth(1, title_text = "Project completed") plant_growth( 0.7, target = 0.9, pot_color = "#4269d0", flower_color = "#efb118", draggable = TRUE )
'pulse_grid()' creates a tiled grid where each cell color reflects a numeric value and the cells gently pulse according to their intensity.
pulse_grid( data, x, y, value, low = "#E0FBFC", high = "#0B525B", stroke = "white", stroke_width = 1, cell_padding = 0.12, corner_radius = 10, pulse = TRUE, pulse_strength = 0.18, show_values = TRUE, digits = 1, value_font_size = 12, x_font_size = 12, y_font_size = 12, title = NULL, title_font_size = 22, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "#0F172A", label_color = "#F8FAFC", title_color = "#F8FAFC", width = NULL, height = NULL )pulse_grid( data, x, y, value, low = "#E0FBFC", high = "#0B525B", stroke = "white", stroke_width = 1, cell_padding = 0.12, corner_radius = 10, pulse = TRUE, pulse_strength = 0.18, show_values = TRUE, digits = 1, value_font_size = 12, x_font_size = 12, y_font_size = 12, title = NULL, title_font_size = 22, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "#0F172A", label_color = "#F8FAFC", title_color = "#F8FAFC", width = NULL, height = NULL )
data |
The data frame containing the grid coordinates and values. |
x |
The column name mapped to the grid columns. |
y |
The column name mapped to the grid rows. |
value |
The numeric column name mapped to tile intensity. |
low |
The low end color of the value scale. Defaults to '#E0FBFC'. |
high |
The high end color of the value scale. Defaults to '#0B525B'. |
stroke |
The border color of each tile. Defaults to 'white'. |
stroke_width |
Border width of each tile. Defaults to 1. |
cell_padding |
Space between tiles, from 0 to 0.9. Defaults to 0.12. |
corner_radius |
Corner radius of each tile. Defaults to 10. |
pulse |
Logical. Whether to animate the tiles. Defaults to 'TRUE'. |
pulse_strength |
Numeric multiplier controlling pulse amplitude. Defaults to 0.18. |
show_values |
Logical. Whether to print values inside tiles. Defaults to 'TRUE'. |
digits |
Number of digits used for in-cell labels. Defaults to 1. |
value_font_size |
Font size of in-cell labels. Defaults to 12. |
x_font_size |
Font size of the column labels. Defaults to 12. |
y_font_size |
Font size of the row labels. Defaults to 12. |
title |
Optional. The title of the plot. |
title_font_size |
Font size of the plot title. Defaults to 22. |
font |
The font family used in labels and title. Defaults to 'Verdana, Geneva, Tahoma, sans-serif'. |
bg_col |
Background color of the SVG. Defaults to '#0F172A'. |
label_color |
Color of the row and column labels. Defaults to '#F8FAFC'. |
title_color |
Color of the title. Defaults to '#F8FAFC'. |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
A SVG pulse grid.
pulse_data <- expand.grid( hour = c("09:00", "12:00", "15:00", "18:00"), team = c("North", "South", "East") ) pulse_data$load <- c(0.35, 0.72, 0.56, 0.91, 0.41, 0.67, 0.83, 0.58, 0.28, 0.49, 0.77, 0.63) pulse_grid( data = pulse_data, x = "hour", y = "team", value = "load", title = "Team Activity Pulse Grid", low = "#D9F0FF", high = "#EE6C4D", bg_col = "#0B132B" )pulse_data <- expand.grid( hour = c("09:00", "12:00", "15:00", "18:00"), team = c("North", "South", "East") ) pulse_data$load <- c(0.35, 0.72, 0.56, 0.91, 0.41, 0.67, 0.83, 0.58, 0.28, 0.49, 0.77, 0.63) pulse_grid( data = pulse_data, x = "hour", y = "team", value = "load", title = "Team Activity Pulse Grid", low = "#D9F0FF", high = "#EE6C4D", bg_col = "#0B132B" )
A radar chart (also called a spider or web chart) compares several quantitative variables at once by placing each one on its own spoke radiating from a common center. Each series (a row of the data) is drawn as a closed, translucent polygon joining its values on every spoke, so series can be compared by their overall shape and footprint. Concentric grid rings mark the scale. The look and feel is inspired by the radar chart of the Chart.js JavaScript library, reimplemented here in plain D3.
The chart is interactive: the polygons grow out from the center on first render, hovering a point shows a tooltip with its value while the other series fade, hovering a polygon focuses that series, and clicking a legend entry toggles the corresponding series on or off.
radar_chart( data, group, axes = NULL, axis_labels = NULL, max_value = NULL, scale_each_axis = FALSE, levels = 5, grid_shape = c("polygon", "circle"), colors = NULL, fill_opacity = 0.2, line_width = 2, point_radius = 3, show_ticks = TRUE, value_format = ",", grid_col = "#dddddd", hover = TRUE, animate = TRUE, legend = TRUE, legend_font_size = 12, label_font_size = 12, tick_font_size = 10, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )radar_chart( data, group, axes = NULL, axis_labels = NULL, max_value = NULL, scale_each_axis = FALSE, levels = 5, grid_shape = c("polygon", "circle"), colors = NULL, fill_opacity = 0.2, line_width = 2, point_radius = 3, show_ticks = TRUE, value_format = ",", grid_col = "#dddddd", hover = TRUE, animate = TRUE, legend = TRUE, legend_font_size = 12, label_font_size = 12, tick_font_size = 10, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider, in wide format (one row per series). |
group |
The name of the column holding the series labels. Its values must be unique (one row per series). |
axes |
Optional. A character vector of at least three numeric column
names, each drawn as a spoke of the radar. Defaults to |
axis_labels |
Optional. A character vector, the same length as
|
max_value |
Optional. The value of the outer ring. With a shared scale,
a single positive number; with |
scale_each_axis |
Whether every axis gets its own scale running from 0 to
that axis' (nice) maximum. Useful when the axes are measured in different
units. The ring tick labels are then hidden and each axis label shows its
maximum instead. Defaults to |
levels |
The number of concentric grid rings. Defaults to |
grid_shape |
Shape of the grid rings, either |
colors |
Optional. A vector of colors, one per series (recycled if
shorter). Defaults to |
fill_opacity |
Opacity of the polygon fills, between 0 and 1. Defaults
to |
line_width |
Width of the polygon outlines in pixels. Defaults to
|
point_radius |
Radius of the point markers in pixels. Defaults to
|
show_ticks |
Whether to print the value of each grid ring along the top
spoke (shared scale only). Defaults to |
value_format |
A d3-format specifier used to display values in the
ticks and the tooltip, e.g. |
grid_col |
Color of the grid rings and spokes. Defaults to
|
hover |
Whether to show a tooltip and highlight the hovered series.
Defaults to |
animate |
Whether the polygons grow out from the center on first
render. Defaults to |
legend |
Whether to display a clickable legend of the series. Defaults
to |
legend_font_size |
Font size of the legend text. Defaults to |
label_font_size |
Font size of the axis labels. Defaults to |
tick_font_size |
Font size of the grid ring tick labels. Defaults to
|
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of the axis labels, tick labels, legend text and
title. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG radar chart.
# Skill ratings of three football players (shared 0-100 scale) players <- data.frame( player = c("Ana", "Ben", "Chloe"), speed = c(88, 72, 65), power = c(60, 91, 70), passing = c(79, 58, 93), dribbling = c(92, 64, 81), defending = c(45, 83, 74), stamina = c(70, 77, 88) ) radar_chart( data = players, group = "player", axes = c("speed", "power", "passing", "dribbling", "defending", "stamina"), max_value = 100, title = "Player skill ratings" ) # Variables measured in different units: give every axis its own scale cyl_means <- aggregate(cbind(mpg, hp, wt, qsec, disp) ~ cyl, data = mtcars, FUN = mean) cyl_means$cyl <- paste(cyl_means$cyl, "cylinders") radar_chart( data = cyl_means, group = "cyl", axis_labels = c("Miles/gallon", "Horsepower", "Weight (1000 lbs)", "1/4 mile time (s)", "Displacement (cu.in.)"), scale_each_axis = TRUE, levels = 4, grid_shape = "circle", value_format = ".1f", title = "mtcars averages by number of cylinders" )# Skill ratings of three football players (shared 0-100 scale) players <- data.frame( player = c("Ana", "Ben", "Chloe"), speed = c(88, 72, 65), power = c(60, 91, 70), passing = c(79, 58, 93), dribbling = c(92, 64, 81), defending = c(45, 83, 74), stamina = c(70, 77, 88) ) radar_chart( data = players, group = "player", axes = c("speed", "power", "passing", "dribbling", "defending", "stamina"), max_value = 100, title = "Player skill ratings" ) # Variables measured in different units: give every axis its own scale cyl_means <- aggregate(cbind(mpg, hp, wt, qsec, disp) ~ cyl, data = mtcars, FUN = mean) cyl_means$cyl <- paste(cyl_means$cyl, "cylinders") radar_chart( data = cyl_means, group = "cyl", axis_labels = c("Miles/gallon", "Horsepower", "Weight (1000 lbs)", "1/4 mile time (s)", "Displacement (cu.in.)"), scale_each_axis = TRUE, levels = 4, grid_shape = "circle", value_format = ".1f", title = "mtcars averages by number of cylinders" )
A radial bar chart (sometimes called a multi-ring progress chart or
"activity rings") draws each category as a concentric circular track. A
faint background track shows the full scale, and a colored arc with
rounded ends sweeps along it in proportion to the category's value
relative to max. It is a compact way to compare a handful of
progress or completion rates. The look is inspired by the radialBar chart
of the ApexCharts JavaScript library, reimplemented here in plain D3.
The first row of data is drawn as the outermost ring. The arcs
sweep in on load, each ring is labelled at the start of its track, and
the center shows the average (or total) of the values. Hovering a ring
highlights it, replaces the center text with that ring's name and value,
and shows a tooltip.
By default the rings cover 270 degrees (start_angle = 0,
end_angle = 270), leaving the top-left quadrant free for the ring
labels. Angles are in degrees, measured clockwise from 12 o'clock. Use
end_angle = 360 for full circles (labels then follow the curve of
each track), or for example start_angle = -90, end_angle = 90 for a
semicircle gauge.
radial_bar_chart( data, label, value, max = 100, start_angle = 0, end_angle = 270, colors = NULL, track_col = "#ececec", hollow = 0.35, ring_gap = 0.3, rounded_caps = TRUE, show_labels = TRUE, show_values = TRUE, label_font_size = 12, center_value = c("average", "total", "none"), center_label = NULL, center_font_size = NULL, value_format = ",.0f", suffix = NULL, hover = TRUE, animate = TRUE, duration = 1200, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )radial_bar_chart( data, label, value, max = 100, start_angle = 0, end_angle = 270, colors = NULL, track_col = "#ececec", hollow = 0.35, ring_gap = 0.3, rounded_caps = TRUE, show_labels = TRUE, show_values = TRUE, label_font_size = 12, center_value = c("average", "total", "none"), center_label = NULL, center_font_size = NULL, value_format = ",.0f", suffix = NULL, hover = TRUE, animate = TRUE, duration = 1200, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
The data frame containing the variables to consider (one row per ring). |
label |
The name of the column holding the ring labels. |
value |
The name of the numeric (non-negative) column holding the ring values. |
max |
The value that corresponds to a full sweep of the track.
Values above |
start_angle |
Angle in degrees at which every track starts, measured
clockwise from 12 o'clock. Defaults to |
end_angle |
Angle in degrees at which every track ends. Must be greater
than |
colors |
Optional. A vector of colors, one per ring (recycled if
shorter). Defaults to |
track_col |
Color of the background tracks. Defaults to
|
hollow |
Size of the empty center as a fraction (0 to 0.9) of the
outer radius. Defaults to |
ring_gap |
Fraction (0 to 0.9) of each ring's band left empty between
neighbouring tracks. Defaults to |
rounded_caps |
Whether the arcs (and partial tracks) have rounded ends.
Defaults to |
show_labels |
Whether to label each ring at the start of its track.
Defaults to |
show_values |
Whether to append the formatted value to each ring
label (e.g. |
label_font_size |
Font size of the ring labels. Defaults to |
center_value |
What to show in the center when nothing is hovered:
|
center_label |
Optional. Text shown above the center value. Defaults
to |
center_font_size |
Optional. Font size of the big center value.
Defaults to |
value_format |
A d3-format specifier used to display values. Defaults
to |
suffix |
Optional. Text appended to every displayed value. Defaults to
|
hover |
Whether hovering a ring highlights it, updates the center
text and shows a tooltip. Defaults to |
animate |
Whether the arcs sweep in on first render. Defaults to
|
duration |
Duration of the sweep animation in milliseconds. Defaults
to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
text_col |
Color of the title, labels and center text. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG radial bar chart.
# Share of users active on each platform (percentages) platforms <- data.frame( platform = c("Vimeo", "Messenger", "Facebook", "LinkedIn"), share = c(76, 67, 61, 90) ) radial_bar_chart( data = platforms, label = "platform", value = "share", title = "Weekly active users (share of total)" ) # Full circles, total in the center, custom colors and a custom maximum sales <- data.frame( region = c("North", "South", "East", "West", "Central"), units = c(420, 310, 275, 190, 120) ) radial_bar_chart( data = sales, label = "region", value = "units", max = 500, end_angle = 360, center_value = "total", center_label = "Units sold", colors = c("#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e"), title = "Units sold by region (target: 500)" ) # Gauge layout open at the bottom, without values in the ring labels radial_bar_chart( data = platforms, label = "platform", value = "share", start_angle = -135, end_angle = 135, hollow = 0.45, show_values = FALSE, track_col = "#f2f2f2" )# Share of users active on each platform (percentages) platforms <- data.frame( platform = c("Vimeo", "Messenger", "Facebook", "LinkedIn"), share = c(76, 67, 61, 90) ) radial_bar_chart( data = platforms, label = "platform", value = "share", title = "Weekly active users (share of total)" ) # Full circles, total in the center, custom colors and a custom maximum sales <- data.frame( region = c("North", "South", "East", "West", "Central"), units = c(420, 310, 275, 190, 120) ) radial_bar_chart( data = sales, label = "region", value = "units", max = 500, end_angle = 360, center_value = "total", center_label = "Units sold", colors = c("#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e"), title = "Units sold by region (target: 500)" ) # Gauge layout open at the bottom, without values in the ring labels radial_bar_chart( data = platforms, label = "platform", value = "share", start_angle = -135, end_angle = 135, hollow = 0.45, show_values = FALSE, track_col = "#f2f2f2" )
A circular bar chart race: at every period, the top top_n items are
drawn around a central circle, sorted by value clockwise from the top, and
they glide to their new place when their rank changes. Two layouts are
available: "spokes", where each item is a bar radiating from the
inner circle (its length is the value), and "rings", where each
item is a concentric arc (the outermost ring is the leader, the length of
the arc is the value). The centre shows the period and the total of the
items on show. The values are interpolated between periods, so playing and
scrubbing are smooth; items entering or leaving the top slide in from, or
out to, the gap at the top of the circle.
radial_bar_race( data, label, value, time, group = NULL, top_n = 12, layout = c("spokes", "rings"), inner_radius = 0.25, scale = c("linear", "area"), max = NULL, agg = c("sum", "mean", "max", "min", "last"), fill_gaps = TRUE, fill = NULL, color_category = NULL, highlight = NULL, center_value = c("total", "average", "none"), legend = NULL, layout_buttons = TRUE, frame_dur = 900, ease = "CubicInOut", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )radial_bar_race( data, label, value, time, group = NULL, top_n = 12, layout = c("spokes", "rings"), inner_radius = 0.25, scale = c("linear", "area"), max = NULL, agg = c("sum", "mean", "max", "min", "last"), fill_gaps = TRUE, fill = NULL, color_category = NULL, highlight = NULL, center_value = c("total", "average", "none"), legend = NULL, layout_buttons = TRUE, frame_dur = 900, ease = "CubicInOut", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )
data |
A data frame in long format: one row per item and period. |
label |
The name of the column identifying the items (one bar per value). |
value |
The name of the numeric column to race. Negative values are drawn as zero. |
time |
The name of the column giving the period: numbers (e.g.
years), dates ( |
group |
Optional. The name of a column grouping the items (e.g. a continent): the bars are then coloured by group, with a clickable legend. |
top_n |
The number of items on show at every period. Defaults to 12. |
layout |
The initial layout: |
inner_radius |
The radius of the central circle: a number below 1 is a fraction of the radius of the chart, a larger number is a radius in pixels. Defaults to 0.25. |
scale |
How the values are mapped to the length of the spokes:
|
max |
Optional. A fixed maximum value for the scale (e.g. 100 for percentages). By default the scale follows the leader of each period, smoothly. |
agg |
How rows with the same item and period are combined:
|
fill_gaps |
Logical. Interpolate the values of an item between the
periods where it is known. Defaults to |
fill |
Optional. The colours: a single colour, a vector of colours
(recycled), or a named vector mapping colours to items (or to groups,
with |
color_category |
Optional. The name of a D3 categorical colour scheme,
such as "Tableau10", "Set2" or "Paired", used when |
highlight |
Optional. A character vector of items to pin from the start. |
center_value |
What the centre shows under the period:
|
legend |
Logical. Show the legend of the groups. When |
layout_buttons |
Logical. Show the Spokes / Rings buttons. Defaults to
|
frame_dur |
The duration of one period, in milliseconds. Defaults to 900. |
ease |
The easing used within a period, the name of a D3 easing
function without the "ease" prefix, e.g. |
autoplay |
Logical. Start playing when the chart scrolls into view.
Defaults to |
loop |
Logical. Start again at the end. Defaults to |
controls |
Logical. Show the player (play / pause, timeline, speed,
loop). Defaults to |
start_frame |
The period shown first: |
time_format |
Optional. A d3-time-format string for date periods, e.g.
|
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 20. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
axis_col |
The colour of the texts, grid and controls. Defaults to "#333333". |
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
tooltip |
Logical. Show a tooltip on hover. Defaults to |
width |
Optional. The width of the chart. |
height |
Optional. The height of the chart. |
An animated radial bar chart race (an r2d3 htmlwidget).
The player at the bottom plays and pauses the race (also with the space bar), the timeline can be dragged or clicked, the arrow keys step one period, Home and End jump to the first and last periods. The speed (0.5x to 4x) and loop buttons sit on the right.
The Spokes / Rings buttons at the top right morph the chart from one layout to the other, even while it plays.
Hover a bar to highlight it and see a live tooltip with its value, its rank, its change since the previous period and its share of the total; the centre then shows the hovered item.
Click a bar to pin it (click again to unpin): pinned items stay
highlighted and the centre follows the last pinned item, even when it
drops out of the top. highlight pins items from the start.
Small arrows next to the labels show the items that just moved up or down.
With group, click a legend entry to hide or show a group,
double-click it to keep only that group; hovering an entry highlights
its items. The ranks are computed without the hidden groups.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a bar sets input$id_clicked to a list with the
label, group, rank, value, period and
pinned state of the item, and input$id_frame gives the
current period (a list with its index and label). The time,
the layout, the pinned items and the hidden groups are kept when the chart
is re-rendered.
library(gapminder) radial_bar_race( gapminder, label = "country", time = "year", value = "pop", title = "The most populous countries", subtitle = "Population, 1952 to 2007" ) # Coloured by continent, as concentric rings radial_bar_race( gapminder, label = "country", time = "year", value = "gdpPercap", group = "continent", top_n = 10, layout = "rings", value_prefix = "$", value_format = ",.0f", title = "GDP per capita" ) # Character periods and a fixed maximum scores <- data.frame( team = rep(c("Red", "Blue", "Green", "Gold", "Teal"), times = 4), round = rep(c("Round 1", "Round 2", "Round 3", "Round 4"), each = 5), points = c(10, 25, 18, 7, 30, 35, 40, 22, 30, 41, 60, 52, 47, 49, 55, 80, 70, 76, 61, 66) ) radial_bar_race(scores, label = "team", time = "round", value = "points", max = 100, frame_dur = 1400)library(gapminder) radial_bar_race( gapminder, label = "country", time = "year", value = "pop", title = "The most populous countries", subtitle = "Population, 1952 to 2007" ) # Coloured by continent, as concentric rings radial_bar_race( gapminder, label = "country", time = "year", value = "gdpPercap", group = "continent", top_n = 10, layout = "rings", value_prefix = "$", value_format = ",.0f", title = "GDP per capita" ) # Character periods and a fixed maximum scores <- data.frame( team = rep(c("Red", "Blue", "Green", "Gold", "Teal"), times = 4), round = rep(c("Round 1", "Round 2", "Round 3", "Round 4"), each = 5), points = c(10, 25, 18, 7, 30, 35, 40, 22, 30, 41, 60, 52, 47, 49, 55, 80, 70, 76, 61, 66) ) radial_bar_race(scores, label = "team", time = "round", value = "points", max = 100, frame_dur = 1400)
A ridgeline plot (also known as a "joy plot") shows the distribution of a
numeric variable for several groups as a stack of partially overlapping
density curves that share a common x-axis. The nickname comes from the
cover of Joy Division's 1979 album Unknown Pleasures, itself a
reproduction of a 1970 plot of successive radio pulses from the first
discovered pulsar. The format was popularised by Claus Wilke's
ggridges package and by FiveThirtyEight and The Washington Post
graphics desks.
Ridgeline plots are ideal for comparing the shape of many distributions at once (e.g. across months, categories, or experimental conditions) while using far less vertical space than a set of separate histograms.
The kernel density estimates are computed in the browser. Ridges are drawn from the back (top) to the front (bottom), so lower ridges overlap the ones above them. Hovering a ridge (or its label) brings it to the front, dims the others, and shows a small label with the group's number of observations and mean.
ridgeline_plot( data, x, group, bandwidth = NULL, kernel = c("gaussian", "epanechnikov"), overlap = 1.5, fill = "steelblue", fill_opacity = 0.8, line_col = "#333333", line_width = 1, sort = c("none", "mean", "median"), stat = c("none", "mean", "median"), stat_color = "#d62728", hover = TRUE, x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )ridgeline_plot( data, x, group, bandwidth = NULL, kernel = c("gaussian", "epanechnikov"), overlap = 1.5, fill = "steelblue", fill_opacity = 0.8, line_col = "#333333", line_width = 1, sort = c("none", "mean", "median"), stat = c("none", "mean", "median"), stat_color = "#d62728", hover = TRUE, x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
x |
The name of the numeric column whose distribution is displayed. |
group |
The name of the categorical column used to split the data
into one ridge per group. When the column is a factor, its level order is
used (unless |
bandwidth |
Optional. The kernel bandwidth, expressed as the standard
deviation of the kernel (as in |
kernel |
The smoothing kernel, either |
overlap |
How much each ridge may overlap the one above it, in units
of the vertical distance between two consecutive baselines. The tallest
peak of the chart reaches exactly |
fill |
Fill color of the ridges. Either a single color (default
|
fill_opacity |
Fill opacity of the ridges (0 to 1). Defaults to
|
line_col |
Color of the density outline. Defaults to |
line_width |
Width of the density outline in pixels. Defaults to
|
sort |
How to order the ridges from top to bottom. One of
|
stat |
Character. Draws a vertical line inside each ridge at the
|
stat_color |
Color of the mean/median line. Defaults to
|
hover |
Logical. When |
x_title |
Optional. Title of the x-axis. |
x_title_font_size |
Font size of the x-axis title. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
x_font_size |
Font size of the x-axis tick labels. Defaults to |
y_font_size |
Font size of the group labels. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of axis lines, ticks, and labels. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG ridgeline plot.
# Simulated reaction times for five experimental conditions set.seed(2026) reaction <- data.frame( time = c(rnorm(200, 300, 40), rnorm(200, 340, 50), rnorm(200, 380, 35), c(rnorm(100, 360, 25), rnorm(100, 460, 30)), rnorm(200, 420, 60)), condition = rep(c("Baseline", "Noise", "Fatigue", "Dual task", "Night"), each = 200) ) ridgeline_plot( data = reaction, x = "time", group = "condition", sort = "mean", stat = "median", title = "Reaction time by condition", x_title = "Reaction time (ms)" ) # Highway fuel economy by vehicle class library(ggplot2) # for the mpg dataset ridgeline_plot( data = mpg, x = "hwy", group = "class", sort = "median", fill = "#2c7fb8", line_col = "white", fill_opacity = 0.9, overlap = 2, title = "Highway fuel economy by vehicle class", x_title = "Highway miles per gallon" ) # One color per group with a named vector, Epanechnikov kernel ridgeline_plot( data = iris, x = "Petal.Length", group = "Species", kernel = "epanechnikov", fill = c(setosa = "#66c2a5", versicolor = "#fc8d62", virginica = "#8da0cb"), overlap = 1, stat = "mean", x_title = "Petal length (cm)" )# Simulated reaction times for five experimental conditions set.seed(2026) reaction <- data.frame( time = c(rnorm(200, 300, 40), rnorm(200, 340, 50), rnorm(200, 380, 35), c(rnorm(100, 360, 25), rnorm(100, 460, 30)), rnorm(200, 420, 60)), condition = rep(c("Baseline", "Noise", "Fatigue", "Dual task", "Night"), each = 200) ) ridgeline_plot( data = reaction, x = "time", group = "condition", sort = "mean", stat = "median", title = "Reaction time by condition", x_title = "Reaction time (ms)" ) # Highway fuel economy by vehicle class library(ggplot2) # for the mpg dataset ridgeline_plot( data = mpg, x = "hwy", group = "class", sort = "median", fill = "#2c7fb8", line_col = "white", fill_opacity = 0.9, overlap = 2, title = "Highway fuel economy by vehicle class", x_title = "Highway miles per gallon" ) # One color per group with a named vector, Epanechnikov kernel ridgeline_plot( data = iris, x = "Petal.Length", group = "Species", kernel = "epanechnikov", fill = c(setosa = "#66c2a5", versicolor = "#fc8d62", virginica = "#8da0cb"), overlap = 1, stat = "mean", x_title = "Petal length (cm)" )
A Nightingale rose (also called a coxcomb or polar area chart) divides a circle into equal-angle wedges, one per category, and encodes each value by how far its wedge extends from the center. The form is credited to Florence Nightingale, who used it in 1858 to show that far more British soldiers in the Crimean War died of preventable disease than of wounds.
Radii follow a square-root scale so that the area of each wedge,
not its length, is proportional to the value, keeping the visual honest.
When a group column is supplied, each wedge is split into stacked
segments whose areas are again proportional to their values. Dashed
radial grid circles carry value labels, and category labels sit outside
the wedges. The look is inspired by the polar-interval "rose" chart of the
AntV G2 library, reimplemented in plain D3.
The chart is interactive: wedges grow out from the center on first render, hovering a wedge pops it outward and shows a tooltip (with a per-group breakdown when stacked), and, when stacked, hovering a legend entry focuses that group while clicking it toggles the group on or off.
rose_chart( data, category, value, group = NULL, colors = NULL, sort = c("none", "desc", "asc"), inner_radius = 0, start_angle = 0, pad_angle = 0, corner_radius = 0, opacity = 0.9, stroke_col = "white", stroke_width = 1, grid_lines = 4, grid_col = "#e0e0e0", grid_font_size = 10, show_labels = TRUE, label_font_size = 11, value_format = ",.0f", hover = TRUE, animate = TRUE, legend = TRUE, legend_font_size = 11, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )rose_chart( data, category, value, group = NULL, colors = NULL, sort = c("none", "desc", "asc"), inner_radius = 0, start_angle = 0, pad_angle = 0, corner_radius = 0, opacity = 0.9, stroke_col = "white", stroke_width = 1, grid_lines = 4, grid_col = "#e0e0e0", grid_font_size = 10, show_labels = TRUE, label_font_size = 11, value_format = ",.0f", hover = TRUE, animate = TRUE, legend = TRUE, legend_font_size = 11, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. Rows that share the same category (and group) are summed. |
category |
The name of the column holding the categories (one wedge per category). If it is a factor, its levels set the order of the wedges; otherwise they appear in the order found in the data. |
value |
The name of the numeric column holding the (non-negative) values. |
group |
Optional. The name of a categorical column used to split
each wedge into stacked segments. If it is a factor, its levels set the
stacking order (first level innermost). Defaults to |
colors |
Optional. A vector of colors, one per group when
|
sort |
How to order the wedges: |
inner_radius |
Size of an empty hole in the middle, as a fraction of
the outer radius (between 0 and 0.9). Defaults to |
start_angle |
Angle, in degrees clockwise from 12 o'clock, at which
the first wedge starts. Defaults to |
pad_angle |
Gap between adjacent wedges, in radians. Defaults to
|
corner_radius |
Corner rounding of the wedges, in pixels. Defaults to
|
opacity |
Fill opacity of the wedges (0 to 1). Defaults to
|
stroke_col |
Color of the wedge outlines. Defaults to |
stroke_width |
Width of the wedge outlines in pixels. Defaults to
|
grid_lines |
Approximate number of radial grid circles (value rings).
Use |
grid_col |
Color of the grid circles and spokes. Defaults to
|
grid_font_size |
Font size of the grid value labels. Defaults to
|
show_labels |
Whether to display the category labels around the
chart. Defaults to |
label_font_size |
Font size of the category labels. Defaults to
|
value_format |
A d3-format specifier used to display values in the
tooltip (e.g. |
hover |
Whether hovering a wedge pops it outward and shows a
tooltip. Defaults to |
animate |
Whether wedges grow out from the center on first render.
Defaults to |
legend |
Whether to display a legend of the groups (only used when
|
legend_font_size |
Font size of the legend text. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of the title, labels and grid value labels. Defaults
to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG Nightingale rose chart.
# Florence Nightingale's data: deaths in the British army in the East, # April 1854 to March 1855, by cause (as in the HistData package) mon <- c("Apr 1854", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan 1855", "Feb", "Mar") crimea <- data.frame( month = factor(rep(mon, times = 3), levels = mon), cause = factor(rep(c("Preventable disease", "Wounds", "Other causes"), each = 12), levels = c("Preventable disease", "Wounds", "Other causes")), deaths = c(1, 12, 11, 359, 828, 788, 503, 844, 1725, 2761, 2120, 1205, 0, 0, 0, 0, 1, 81, 132, 287, 114, 83, 42, 32, 5, 9, 6, 23, 30, 70, 128, 106, 131, 324, 361, 172) ) rose_chart( data = crimea, category = "month", value = "deaths", group = "cause", colors = c("#7fa7c9", "#e0645c", "#4d4d4d"), title = "Causes of death in the army in the East, 1854-55", height = 560 ) # A simple rose: one wedge per category, sorted by value rose_chart( data = data.frame(state = rownames(USArrests)[1:12], murder = USArrests$Murder[1:12]), category = "state", value = "murder", sort = "desc", value_format = ".1f", title = "Murder arrests per 100,000 residents (1973)" ) # Donut-style rose with a hole, gaps and rounded corners rose_chart( data = as.data.frame(table(cyl = mtcars$cyl, gear = mtcars$gear)), category = "gear", value = "Freq", group = "cyl", inner_radius = 0.25, pad_angle = 0.03, corner_radius = 4, title = "Cars by number of gears and cylinders" )# Florence Nightingale's data: deaths in the British army in the East, # April 1854 to March 1855, by cause (as in the HistData package) mon <- c("Apr 1854", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan 1855", "Feb", "Mar") crimea <- data.frame( month = factor(rep(mon, times = 3), levels = mon), cause = factor(rep(c("Preventable disease", "Wounds", "Other causes"), each = 12), levels = c("Preventable disease", "Wounds", "Other causes")), deaths = c(1, 12, 11, 359, 828, 788, 503, 844, 1725, 2761, 2120, 1205, 0, 0, 0, 0, 1, 81, 132, 287, 114, 83, 42, 32, 5, 9, 6, 23, 30, 70, 128, 106, 131, 324, 361, 172) ) rose_chart( data = crimea, category = "month", value = "deaths", group = "cause", colors = c("#7fa7c9", "#e0645c", "#4d4d4d"), title = "Causes of death in the army in the East, 1854-55", height = 560 ) # A simple rose: one wedge per category, sorted by value rose_chart( data = data.frame(state = rownames(USArrests)[1:12], murder = USArrests$Murder[1:12]), category = "state", value = "murder", sort = "desc", value_format = ".1f", title = "Murder arrests per 100,000 residents (1973)" ) # Donut-style rose with a hole, gaps and rounded corners rose_chart( data = as.data.frame(table(cyl = mtcars$cyl, gear = mtcars$gear)), category = "gear", value = "Freq", group = "cyl", inner_radius = 0.25, pad_angle = 0.03, corner_radius = 4, title = "Cars by number of gears and cylinders" )
Draws flows between nodes as bands whose width is proportional to their value: each node is a bar as tall as the largest of what flows into it and out of it, and the nodes are laid out in columns from left to right. Use it for budgets, energy balances, user journeys or any process where quantities split and merge. The flows must not form a cycle.
sankey_diagram( data, source, target, value = NULL, colors = NULL, link_color = c("source", "target", "gradient", "grey"), align = c("justify", "left", "right", "center"), node_width = 14, node_padding = 12, link_opacity = 0.4, show_values = TRUE, value_format = ",.0f", label_font_size = 11, draggable = TRUE, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )sankey_diagram( data, source, target, value = NULL, colors = NULL, link_color = c("source", "target", "gradient", "grey"), align = c("justify", "left", "right", "center"), node_width = 14, node_padding = 12, link_opacity = 0.4, show_values = TRUE, value_format = ",.0f", label_font_size = 11, draggable = TRUE, hover = TRUE, animate = TRUE, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "#333333", width = NULL, height = NULL )
data |
A data frame with one row per flow. |
source, target
|
The names of the columns giving the start and the end of each flow. |
value |
Optional. The name of a numeric column giving the size of each
flow. When |
colors |
Optional. Colours of the nodes: one per node (in order of appearance) or a named vector matched to the node names. |
link_color |
How to colour the flows: |
align |
How to place the nodes in columns: |
node_width |
The width of the nodes in pixels. Defaults to 14. |
node_padding |
The vertical gap between nodes in pixels. Defaults to 12. |
link_opacity |
The opacity of the flows. Defaults to 0.4. |
show_values |
Logical. Write the value of each node under its name. Defaults to TRUE. |
value_format |
A d3 format for the values. Defaults to ",.0f". |
label_font_size |
The font size of the node labels. Defaults to 11. |
draggable |
Logical. Let the viewer drag the nodes up and down. Defaults to TRUE. |
hover |
Logical. Show tooltips and highlight on hover. Defaults to TRUE. |
animate |
Logical. Let the flows run in when the chart is drawn. Defaults to TRUE. |
title |
Optional. The title of the chart. |
title_font_size |
The font size of the title. Defaults to 16. |
font |
The font family. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour. Defaults to "white". |
text_col |
The colour of the text. Defaults to "#333333". |
width, height
|
Optional. The size of the chart. |
An r2d3 htmlwidget.
Hover a flow to see its value and its share of the source and the target;
hover a node to highlight everything that flows into it and out of it. Drag
a node up or down to untangle the diagram (draggable). The flows run
from left to right when the chart is drawn. Inside Shiny, clicking a node
sets input$<id>_clicked to a list with node and value,
and clicking a flow sets it to a list with source, target and
value.
# A household budget budget <- data.frame( from = c("Salary", "Salary", "Freelance", "Freelance", "Savings", "Savings", "Living", "Living", "Living"), to = c("Living", "Savings", "Living", "Savings", "Stocks", "Emergency fund", "Rent", "Food", "Transport"), amount = c(2600, 900, 500, 300, 700, 500, 1700, 900, 500) ) sankey_diagram(budget, source = "from", target = "to", value = "amount", value_format = "$,.0f", title = "Where the money goes") # Who survived the Titanic: class, then sex, then outcome tt <- as.data.frame(Titanic) tt$Survived <- ifelse(tt$Survived == "Yes", "Survived", "Died") step1 <- aggregate(Freq ~ Class + Sex, data = tt, FUN = sum) step2 <- aggregate(Freq ~ Sex + Survived, data = tt, FUN = sum) names(step1) <- names(step2) <- c("from", "to", "people") sankey_diagram(rbind(step1, step2), source = "from", target = "to", value = "people", link_color = "gradient", colors = c(Died = "#9498a0", Survived = "#3ca951"))# A household budget budget <- data.frame( from = c("Salary", "Salary", "Freelance", "Freelance", "Savings", "Savings", "Living", "Living", "Living"), to = c("Living", "Savings", "Living", "Savings", "Stocks", "Emergency fund", "Rent", "Food", "Transport"), amount = c(2600, 900, 500, 300, 700, 500, 1700, 900, 500) ) sankey_diagram(budget, source = "from", target = "to", value = "amount", value_format = "$,.0f", title = "Where the money goes") # Who survived the Titanic: class, then sex, then outcome tt <- as.data.frame(Titanic) tt$Survived <- ifelse(tt$Survived == "Yes", "Survived", "Died") step1 <- aggregate(Freq ~ Class + Sex, data = tt, FUN = sum) step2 <- aggregate(Freq ~ Sex + Survived, data = tt, FUN = sum) names(step1) <- names(step2) <- c("from", "to", "people") sankey_diagram(rbind(step1, step2), source = "from", target = "to", value = "people", link_color = "gradient", colors = c(Died = "#9498a0", Survived = "#3ca951"))
Plots two numeric variables against each other. Points can be coloured by a group (categorical or continuous), sized by a third variable (bubble chart), labelled, and summarised with a linear or LOESS trend line and its confidence band. The chart is interactive: hovering a point shows its values, the legend hides or isolates groups, and dragging a box selects points, which can then be zoomed into.
scatter_plot( data, x, y, col = NULL, size = 4, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 0.8, axis_col = "#333333", width = NULL, height = NULL, group = NULL, size_by = NULL, size_range = c(3, 16), label = NULL, show_labels = NULL, tooltip = TRUE, trend = c("none", "lm", "loess"), ci = TRUE, span = 0.75, x_scale = c("linear", "log"), y_scale = c("linear", "log"), h_lines = NULL, v_lines = NULL, legend = NULL, brush = TRUE, animate = TRUE, x_format = NULL, y_format = NULL, subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )scatter_plot( data, x, y, col = NULL, size = 4, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, stroke = NULL, stroke_width = NULL, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 0.8, axis_col = "#333333", width = NULL, height = NULL, group = NULL, size_by = NULL, size_range = c(3, 16), label = NULL, show_labels = NULL, tooltip = TRUE, trend = c("none", "lm", "loess"), ci = TRUE, span = 0.75, x_scale = c("linear", "log"), y_scale = c("linear", "log"), h_lines = NULL, v_lines = NULL, legend = NULL, brush = TRUE, animate = TRUE, x_format = NULL, y_format = NULL, subtitle = NULL, subtitle_font_size = 13, grid_col = "#e9e9e9" )
data |
The data frame containing the variables. |
x |
The name of the numeric x-variable. |
y |
The name of the numeric y-variable. |
col |
Colour of the points. A single colour when there is no
|
size |
The radius of the points in pixels when |
x_ticks |
Optional. The approximate number of x-axis ticks. |
y_ticks |
Optional. The approximate number of y-axis ticks. |
x_title |
Optional. The title of the x-axis. Defaults to the name of
|
x_title_font_size |
The font size of the x-axis title. Defaults to 13. |
y_title |
Optional. The title of the y-axis, drawn above the axis.
Defaults to the name of |
y_title_font_size |
The font size of the y-axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
stroke |
Optional. The stroke colour of the points. Defaults to the background colour, which separates overlapping points. |
stroke_width |
Optional. The stroke width of the points. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
opacity |
The opacity of the points (from 0 to 1). Defaults to 0.8. |
axis_col |
The colour of the axes, labels and titles. Defaults to "#333333". |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
group |
Optional. The name of a column used to colour the points. A
character, factor or logical column gives one colour per group and a
clickable legend; a numeric column gives a colour gradient. Use
|
size_by |
Optional. The name of a numeric column mapped to the point area (bubble chart). |
size_range |
The minimum and maximum radius in pixels used with
|
label |
Optional. The name of a column identifying each point. It is
used as the tooltip title and by |
show_labels |
Optional. Draws text labels next to points:
|
tooltip |
|
trend |
Adds a trend line: |
ci |
Logical. Draw the 95% confidence band around the trend line.
Defaults to |
span |
The LOESS smoothing parameter. Defaults to 0.75. |
x_scale |
The x-axis scale: |
y_scale |
The y-axis scale: |
h_lines |
Optional. Numeric values drawn as horizontal dashed reference lines; names are used as labels. |
v_lines |
Optional. Numeric values drawn as vertical dashed reference lines; names are used as labels. |
legend |
Logical. Show the legend. When |
brush |
Logical. Enable drag-to-select and zoom. Defaults to
|
animate |
Logical. Animate the points when the chart is first drawn.
Defaults to |
x_format, y_format
|
Optional. d3-format strings for the axes and the
tooltip, e.g. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
grid_col |
The colour of the grid lines. Defaults to "#e9e9e9"; use
|
An interactive SVG scatter plot (an r2d3 htmlwidget).
Hover a point to see its values; hover a trend line to see the fit
(slope, intercept and R-squared for trend = "lm").
Click a legend entry to hide or show a group, double-click it to isolate it. Hovering a legend entry highlights the group.
Drag on the chart to select points (when brush = TRUE). The
toolbar then offers Zoom and Clear. Double-click the chart
to reset the zoom.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
the chart sets two inputs: input$id_selected, the row numbers of
data inside the brushed box (NULL when the selection is
cleared), and input$id_clicked, the row number of the last clicked
point. Hidden groups and the zoom are kept when the chart is re-rendered
with the same x and y.
scatter_plot( data = mtcars, x = "wt", y = "mpg" ) # Colour by group, one linear fit per group scatter_plot( data = iris, x = "Sepal.Length", y = "Petal.Length", group = "Species", trend = "lm", title = "Petal and sepal length" ) # Bubble chart with a continuous colour scale, labels and extra tooltip rows cars <- mtcars cars$model <- rownames(mtcars) scatter_plot( data = cars, x = "hp", y = "mpg", size_by = "disp", group = "qsec", label = "model", show_labels = c("Maserati Bora", "Toyota Corolla", "Lotus Europa"), tooltip = c("cyl", "gear"), trend = "loess", title = "Horsepower and fuel economy", subtitle = "Bubble area: displacement; colour: quarter-mile time" ) # Log scales and reference lines scatter_plot( data = data.frame(area = state.x77[, "Area"], population = state.x77[, "Population"], state = rownames(state.x77)), x = "area", y = "population", label = "state", x_scale = "log", y_scale = "log", h_lines = c("Median" = 2838.5) )scatter_plot( data = mtcars, x = "wt", y = "mpg" ) # Colour by group, one linear fit per group scatter_plot( data = iris, x = "Sepal.Length", y = "Petal.Length", group = "Species", trend = "lm", title = "Petal and sepal length" ) # Bubble chart with a continuous colour scale, labels and extra tooltip rows cars <- mtcars cars$model <- rownames(mtcars) scatter_plot( data = cars, x = "hp", y = "mpg", size_by = "disp", group = "qsec", label = "model", show_labels = c("Maserati Bora", "Toyota Corolla", "Lotus Europa"), tooltip = c("cyl", "gear"), trend = "loess", title = "Horsepower and fuel economy", subtitle = "Bubble area: displacement; colour: quarter-mile time" ) # Log scales and reference lines scatter_plot( data = data.frame(area = state.x77[, "Area"], population = state.x77[, "Population"], state = rownames(state.x77)), x = "area", y = "population", label = "state", x_scale = "log", y_scale = "log", h_lines = c("Median" = 2838.5) )
A slope chart (or slopegraph) compares two values per category by placing them on two vertical axes, typically "before" and "after" or two years, and connecting them with a straight line. The steepness and direction of each line show at a glance which categories rose, which fell, and how their ranking changed. The form was popularised by Edward Tufte in The Visual Display of Quantitative Information (1983) and is a staple of the New York Times graphics desk.
Each line is labelled with its category name and value at both ends;
labels that would overlap are nudged apart vertically. Lines can be colored
by direction (increase, decrease, no change), a subset of categories can
be emphasised with highlight, and hovering over a line fades the
others.
slope_chart( data, start, end, group, start_label = NULL, end_label = NULL, color_by_direction = TRUE, up_col = "#1a9850", down_col = "#d73027", flat_col = "#888888", line_col = "steelblue", highlight = NULL, muted_col = "#cccccc", line_width = 2, circle_radius = 4, show_values = TRUE, digits = NULL, label_font_size = 11, header_font_size = 13, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )slope_chart( data, start, end, group, start_label = NULL, end_label = NULL, color_by_direction = TRUE, up_col = "#1a9850", down_col = "#d73027", flat_col = "#888888", line_col = "steelblue", highlight = NULL, muted_col = "#cccccc", line_width = 2, circle_radius = 4, show_values = TRUE, digits = NULL, label_font_size = 11, header_font_size = 13, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider, in wide format (one row per category). |
start |
The name of the numeric column holding the values plotted on the left axis. |
end |
The name of the numeric column holding the values plotted on the right axis. |
group |
The name of the column holding the category labels (one line per category). |
start_label |
Header displayed above the left axis. Defaults to the
value of |
end_label |
Header displayed above the right axis. Defaults to the
value of |
color_by_direction |
Whether to color lines by direction of change
( |
up_col |
Color of lines that increase. Defaults to |
down_col |
Color of lines that decrease. Defaults to |
flat_col |
Color of lines with no change. Defaults to |
line_col |
Color of all lines when |
highlight |
Optional. A character vector of categories (values of the
|
muted_col |
Color of non-highlighted lines when |
line_width |
Width of the lines in pixels. Defaults to |
circle_radius |
Radius of the end-point dots in pixels. Defaults to
|
show_values |
Whether to print the value next to each category label.
Defaults to |
digits |
Optional. Number of decimal places used to print the values.
Defaults to |
label_font_size |
Font size of the category and value labels. Defaults
to |
header_font_size |
Font size of the two axis headers. Defaults to
|
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of the two vertical axes, the headers, the title and
the labels. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG slope chart.
# Current receipts of government as a percentage of GDP, 1970 vs 1979 # (adapted from Edward Tufte's classic slopegraph) receipts <- data.frame( country = c("Sweden", "Netherlands", "Norway", "Britain", "France", "Germany", "Belgium", "Canada", "Finland", "Italy", "United States", "Greece", "Switzerland", "Spain", "Japan"), y1970 = c(46.9, 44.0, 43.5, 40.7, 39.0, 37.5, 35.2, 35.2, 34.9, 30.4, 30.3, 26.8, 26.5, 22.5, 20.7), y1979 = c(57.4, 55.8, 52.2, 39.0, 43.4, 42.9, 43.2, 35.8, 38.2, 35.7, 32.5, 30.6, 33.2, 27.1, 26.6) ) slope_chart( data = receipts, start = "y1970", end = "y1979", group = "country", start_label = "1970", end_label = "1979", digits = 1, title = "Government receipts as % of GDP", height = 520 ) # Life expectancy in 1952 vs 2007, highlighting two countries library(gapminder) library(dplyr) library(tidyr) countries <- c("China", "India", "Japan", "Brazil", "Nigeria", "Egypt", "Germany", "United States", "South Africa") life <- filter(gapminder, year %in% c(1952, 2007), country %in% countries) life <- select(life, country, year, lifeExp) life <- pivot_wider(life, names_from = year, values_from = lifeExp, names_prefix = "y") slope_chart( data = life, start = "y1952", end = "y2007", group = "country", start_label = "1952", end_label = "2007", highlight = c("China", "South Africa"), digits = 1, title = "Life expectancy: 1952 vs 2007" )# Current receipts of government as a percentage of GDP, 1970 vs 1979 # (adapted from Edward Tufte's classic slopegraph) receipts <- data.frame( country = c("Sweden", "Netherlands", "Norway", "Britain", "France", "Germany", "Belgium", "Canada", "Finland", "Italy", "United States", "Greece", "Switzerland", "Spain", "Japan"), y1970 = c(46.9, 44.0, 43.5, 40.7, 39.0, 37.5, 35.2, 35.2, 34.9, 30.4, 30.3, 26.8, 26.5, 22.5, 20.7), y1979 = c(57.4, 55.8, 52.2, 39.0, 43.4, 42.9, 43.2, 35.8, 38.2, 35.7, 32.5, 30.6, 33.2, 27.1, 26.6) ) slope_chart( data = receipts, start = "y1970", end = "y1979", group = "country", start_label = "1970", end_label = "1979", digits = 1, title = "Government receipts as % of GDP", height = 520 ) # Life expectancy in 1952 vs 2007, highlighting two countries library(gapminder) library(dplyr) library(tidyr) countries <- c("China", "India", "Japan", "Brazil", "Nigeria", "Egypt", "Germany", "United States", "South Africa") life <- filter(gapminder, year %in% c(1952, 2007), country %in% countries) life <- select(life, country, year, lifeExp) life <- pivot_wider(life, names_from = year, values_from = lifeExp, names_prefix = "y") slope_chart( data = life, start = "y1952", end = "y2007", group = "country", start_label = "1952", end_label = "2007", highlight = c("China", "South Africa"), digits = 1, title = "Life expectancy: 1952 vs 2007" )
Stacks several time series on top of each other, so you can read both the
total and how each component contributes to it. Buttons on the chart
switch between stacked values and shares of the total (100%). It shares
the interactions of line_chart(): a crosshair tooltip
(every layer with its share, and the total), range buttons, a navigator,
drag-to-zoom (double-click to reset), labels at the end of each layer and
a legend: click an entry to hide a layer, double-click it to keep only
that layer; the other layers re-stack.
stacked_area_chart( data, x = NULL, color_category = NULL, curve = "curveLinear", stroke = NULL, stroke_width = 1, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 0.85, axis_col = "#333333", legend_box_size = NULL, legend_text_size = NULL, width = NULL, height = NULL, y = NULL, group = NULL, colors = NULL, position = c("stacked", "percent"), controls = TRUE, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, grid_col = "#e9e9e9" )stacked_area_chart( data, x = NULL, color_category = NULL, curve = "curveLinear", stroke = NULL, stroke_width = 1, x_ticks = NULL, y_ticks = NULL, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, title = NULL, title_font_size = 20, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", opacity = 0.85, axis_col = "#333333", legend_box_size = NULL, legend_text_size = NULL, width = NULL, height = NULL, y = NULL, group = NULL, colors = NULL, position = c("stacked", "percent"), controls = TRUE, events = NULL, bands = NULL, h_lines = NULL, legend = NULL, end_labels = NULL, tooltip = TRUE, navigator = TRUE, range_buttons = TRUE, zoom = TRUE, animate = TRUE, value_format = NULL, value_prefix = "", value_suffix = "", date_format = NULL, subtitle = NULL, subtitle_font_size = 13, x_font_size = 11, y_font_size = 11, grid_col = "#e9e9e9" )
data |
A data frame, or a |
x |
The time variable: a |
color_category |
Optional. The name of a D3 categorical colour scheme
(for example "Tableau10", "Set2" or "Accent", see
<https://github.com/d3/d3-scale-chromatic#categorical>), used when
|
curve |
The curve type of the layers. Defaults to 'curveLinear'; 'curveMonotoneX' gives smooth layers that never cross. A complete list can be found here <https://github.com/d3/d3-shape#curves>. |
stroke |
Optional. The colour of the line drawn on top of every layer, for example "white" to separate the layers. Defaults to the colour of each layer. |
stroke_width |
The width of the line on top of every layer. Defaults to 1. |
x_ticks |
Optional. The approximate number of x-axis ticks. |
y_ticks |
Optional. The approximate number of y-axis ticks. |
x_title |
Optional. The title of the x-axis. |
x_title_font_size |
The font size of the x-axis title. Defaults to 13. |
y_title |
Optional. The title of the y-axis, shown above the axis. |
y_title_font_size |
The font size of the y-axis title. Defaults to 13. |
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
font |
The font family to consider for the titles. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background color of the SVG. Defaults to "white". |
opacity |
The opacity of the layers (from 0 to 1). Defaults to 0.85. |
axis_col |
The color of the axis text, ticks and titles. Defaults to "#333333". |
legend_box_size, legend_text_size
|
Not used; kept for compatibility. |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
y |
Optional. The value columns (wide data), or the single value
column of long data with |
group |
Optional. For long data, the column whose values name the layers. |
colors |
Optional. Colours of the layers, an unnamed vector (recycled) or a vector named by layer. |
position |
"stacked" (default) or "percent" (shares of the total).
It can be changed from the chart when |
controls |
Logical. Show the Stacked / 100% buttons. Defaults to
|
events |
Optional. Dates to mark with a vertical line: either a vector of dates (names are used as labels) or a data frame whose first column holds the dates and whose second column (optional) holds labels. |
bands |
Optional. Periods to shade, as a data frame whose first two columns are the start and end dates. An optional third column holds the labels and an optional fourth column the fill colors. |
h_lines |
Optional. Numeric reference values drawn as horizontal
dashed lines (names are used as labels). Only drawn when
|
legend |
Logical. Show the interactive legend (click to hide or show
a series, double-click to isolate it). When |
end_labels |
Logical. Label each line at its last visible point. When
|
tooltip |
Logical. Show the crosshair and the tooltip on hover.
Defaults to |
navigator |
Logical. Show the navigator (a miniature of the full
series with a brush to select the visible range) under the chart.
Defaults to |
range_buttons |
Logical. Show range buttons (1M, 6M, YTD, 1Y, 5Y,
All, ...), chosen from the length and frequency of the data. Only used
with dates. Defaults to |
zoom |
Logical. Drag horizontally on the chart to zoom into a range;
double-click to reset. Defaults to |
animate |
Logical. Draw the lines in with an animation on first
render. Defaults to |
value_format |
Optional. A d3-format string for values in the tooltip
(see <https://github.com/d3/d3-format>). Defaults to ",.2~f", or "+.2~%"
with |
value_prefix, value_suffix
|
Optional. Text placed before and after the values on the y axis and in the tooltip, for example "$" or " km". |
date_format |
Optional. A d3-time-format string for the date in the
tooltip (see <https://github.com/d3/d3-time-format>). When |
subtitle |
Optional. A subtitle shown under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
x_font_size, y_font_size
|
The font size of the axis tick labels. Defaults to 11. |
grid_col |
The color of the horizontal grid lines. Defaults to "#e9e9e9". |
Series can be given as wide data (by default, every numeric column other
than x; or the columns named in y), as long data (one
y column and a group column), or as an mts object.
Missing values count as zero when stacking, and negative values are
stacked below zero.
An interactive SVG stacked area chart.
data <- data.frame( date = c( "2000-01-01", "2000-02-01", "2000-03-01", "2000-04-01", "2000-05-01", "2000-06-01", "2000-07-01", "2000-08-01", "2000-09-01", "2000-10-01" ), Trade = c( 2000,1023, 983, 2793, 1821, 1837, 1792, 1853, 791, 739 ), Manufacturing = c( 734, 694, 739, 736, 685, 621, 708, 685, 667, 693 ), Leisure = c( 1782, 1779, 1789, 658, 675, 833, 786, 675, 636, 691 ), Agriculture = c( 655, 587,623, 517, 561, 2545, 636, 584, 559, 2504 ) ) stacked_area_chart( data = data, x = "date", curve = "curveMonotoneX", stroke = "white", title = "Employment by sector" ) # Long data, shown as shares of the total library(ggplot2) # for the economics_long data set stacked_area_chart( subset(economics_long, variable %in% c("pce", "psavert", "uempmed")), x = "date", y = "value", group = "variable", position = "percent" )data <- data.frame( date = c( "2000-01-01", "2000-02-01", "2000-03-01", "2000-04-01", "2000-05-01", "2000-06-01", "2000-07-01", "2000-08-01", "2000-09-01", "2000-10-01" ), Trade = c( 2000,1023, 983, 2793, 1821, 1837, 1792, 1853, 791, 739 ), Manufacturing = c( 734, 694, 739, 736, 685, 621, 708, 685, 667, 693 ), Leisure = c( 1782, 1779, 1789, 658, 675, 833, 786, 675, 636, 691 ), Agriculture = c( 655, 587,623, 517, 561, 2545, 636, 584, 559, 2504 ) ) stacked_area_chart( data = data, x = "date", curve = "curveMonotoneX", stroke = "white", title = "Employment by sector" ) # Long data, shown as shares of the total library(ggplot2) # for the economics_long data set stacked_area_chart( subset(economics_long, variable %in% c("pce", "psavert", "uempmed")), x = "date", y = "value", group = "variable", position = "percent" )
A streamgraph is a stacked area chart whose baseline is not fixed at zero but displaced around a central axis, so the layers flow like a river. It shows how the composition of a total changes over time while keeping attention on the shape of each layer rather than on exact values. The form was popularised by Lee Byron and Martin Wattenberg's "Stacked Graphs: Geometry & Aesthetics" (2008); this implementation reproduces the look and feel of the Highcharts streamgraph in plain D3.
Unlike stacked_area_chart(), which takes wide data and stacks
areas on a zero baseline, streamgraph() takes long (tidy) data, uses
a centred baseline (offset), orders layers inside out so the largest
layers sit in the middle, and labels each layer inline at its thickest
point instead of relying on a separate legend.
The chart is interactive: hovering a layer highlights it while the others
dim, a vertical crosshair snaps to the nearest x value and shows a tooltip
with the value of every layer at that x, and (when legend = TRUE)
hovering a legend item focuses its layer while clicking it hides or shows
the layer, re-stacking the stream with an animation. Missing
x/group combinations are treated as zero.
streamgraph( data, x, group, value, offset = c("wiggle", "silhouette", "expand"), order = c("insideOut", "none", "reverse", "ascending", "descending"), curve = c("basis", "catmullRom", "monotoneX", "linear", "step"), colors = NULL, color_palette = "Tableau10", opacity = 0.9, stroke_col = "white", stroke_width = 0.5, labels = TRUE, label_font_size = 11, label_col = NULL, tooltip = TRUE, hover = TRUE, animate = TRUE, legend = TRUE, legend_font_size = 11, value_format = ",.2~f", x_format = NULL, x_ticks = NULL, x_font_size = 11, grid_col = "#e6e6e6", x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )streamgraph( data, x, group, value, offset = c("wiggle", "silhouette", "expand"), order = c("insideOut", "none", "reverse", "ascending", "descending"), curve = c("basis", "catmullRom", "monotoneX", "linear", "step"), colors = NULL, color_palette = "Tableau10", opacity = 0.9, stroke_col = "white", stroke_width = 0.5, labels = TRUE, label_font_size = 11, label_col = NULL, tooltip = TRUE, hover = TRUE, animate = TRUE, legend = TRUE, legend_font_size = 11, value_format = ",.2~f", x_format = NULL, x_ticks = NULL, x_font_size = 11, grid_col = "#e6e6e6", x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider, in long format (one row per x value and group). |
x |
The name of the column holding the x values. Must be numeric
(e.g. years), |
group |
The name of the column holding the layer (series) names.
If it is a factor, its level order is used as the layer order when
|
value |
The name of the numeric, non-negative column holding the
thickness of each layer. Rows sharing the same |
offset |
The baseline of the stream. |
order |
The order in which layers are stacked. |
curve |
The curve used to interpolate the layers: |
colors |
Optional. A vector of colors, one per layer (recycled if
shorter). Defaults to |
color_palette |
D3 categorical color scheme used when |
opacity |
Fill opacity of the layers (0 to 1). Defaults to
|
stroke_col |
Color of the thin line separating the layers. Defaults
to |
stroke_width |
Width of the separating line in pixels. Defaults to
|
labels |
Whether to write each layer's name inside the layer, at its
thickest point. Labels that do not fit their layer are hidden. Defaults to
|
label_font_size |
Font size of the inline layer labels. Defaults to
|
label_col |
Optional. Color of the inline labels. Defaults to
|
tooltip |
Whether to show the vertical crosshair and the tooltip
listing every layer's value at the hovered x. Defaults to |
hover |
Whether hovering a layer (or a legend item) highlights it and
dims the others. Defaults to |
animate |
Whether the stream is revealed from left to right on first
render. Defaults to |
legend |
Whether to show an interactive legend under the chart
(hover to focus a layer, click to hide or show it). Defaults to
|
legend_font_size |
Font size of the legend text. Defaults to |
value_format |
A d3-format specifier used to display the values in the
tooltip (e.g. |
x_format |
Optional. Format of the x values on the axis and in the
tooltip header: a d3-format specifier for numeric |
x_ticks |
Optional. Approximate number of x-axis ticks. Defaults to
|
x_font_size |
Font size of the x-axis tick labels. Defaults to
|
grid_col |
Color of the vertical grid lines drawn at each x tick. Use
|
x_title |
Optional. Title of the x-axis. |
x_title_font_size |
Font size of the x-axis title. Defaults to
|
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of the x-axis, the titles, the crosshair and the
legend text. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG streamgraph.
# Popularity of music genres over four decades (simulated) set.seed(2026) years <- 1980:2020 genres <- c("Rock", "Pop", "Hip hop", "Electronic", "Country", "R&B", "Jazz", "Metal", "Reggae", "Latin") peaks <- c(1984, 1999, 2012, 2008, 1993, 2003, 1981, 1990, 1986, 2018) sizes <- c(60, 55, 70, 40, 30, 35, 18, 25, 15, 45) music <- expand.grid(year = years, genre = genres) idx <- match(music$genre, genres) music$listeners <- round( sizes[idx] * exp(-((music$year - peaks[idx]) / 9)^2) + runif(nrow(music), 1, 6) ) streamgraph( data = music, x = "year", group = "genre", value = "listeners", value_format = ",.0f", x_title = "Year", title = "Music genres, 1980-2020 (millions of listeners)" ) # Share of the world's telephones by region (base R data), 100% stream phones <- data.frame( year = rep(as.numeric(rownames(WorldPhones)), ncol(WorldPhones)), region = factor(rep(colnames(WorldPhones), each = nrow(WorldPhones)), levels = colnames(WorldPhones)), phones = as.vector(WorldPhones) ) streamgraph( data = phones, x = "year", group = "region", value = "phones", offset = "expand", order = "descending", curve = "monotoneX", color_palette = "Set2", value_format = ",.0f", title = "Telephones by region, 1951-1961 (thousands)" ) # Date x-axis with a silhouette baseline: weekly sign-ups per channel set.seed(7) weeks <- seq(as.Date("2026-01-01"), by = "week", length.out = 52) channels <- c("Organic", "Paid search", "Social", "Referral", "Email") signups <- expand.grid(week = weeks, channel = channels) t <- as.numeric(signups$week - min(weeks)) / 7 k <- as.integer(signups$channel) signups$n <- round( (60 + 25 * sin(t / 6 + k)) * c(1.4, 1, 0.8, 0.5, 0.6)[k] + rpois(length(t), 6) ) streamgraph( data = signups, x = "week", group = "channel", value = "n", offset = "silhouette", x_format = "%b %Y", colors = c("#2caffe", "#544fc5", "#00e272", "#fe6a35", "#6b8abc"), legend = FALSE, title = "Weekly sign-ups by channel, 2026" )# Popularity of music genres over four decades (simulated) set.seed(2026) years <- 1980:2020 genres <- c("Rock", "Pop", "Hip hop", "Electronic", "Country", "R&B", "Jazz", "Metal", "Reggae", "Latin") peaks <- c(1984, 1999, 2012, 2008, 1993, 2003, 1981, 1990, 1986, 2018) sizes <- c(60, 55, 70, 40, 30, 35, 18, 25, 15, 45) music <- expand.grid(year = years, genre = genres) idx <- match(music$genre, genres) music$listeners <- round( sizes[idx] * exp(-((music$year - peaks[idx]) / 9)^2) + runif(nrow(music), 1, 6) ) streamgraph( data = music, x = "year", group = "genre", value = "listeners", value_format = ",.0f", x_title = "Year", title = "Music genres, 1980-2020 (millions of listeners)" ) # Share of the world's telephones by region (base R data), 100% stream phones <- data.frame( year = rep(as.numeric(rownames(WorldPhones)), ncol(WorldPhones)), region = factor(rep(colnames(WorldPhones), each = nrow(WorldPhones)), levels = colnames(WorldPhones)), phones = as.vector(WorldPhones) ) streamgraph( data = phones, x = "year", group = "region", value = "phones", offset = "expand", order = "descending", curve = "monotoneX", color_palette = "Set2", value_format = ",.0f", title = "Telephones by region, 1951-1961 (thousands)" ) # Date x-axis with a silhouette baseline: weekly sign-ups per channel set.seed(7) weeks <- seq(as.Date("2026-01-01"), by = "week", length.out = 52) channels <- c("Organic", "Paid search", "Social", "Referral", "Email") signups <- expand.grid(week = weeks, channel = channels) t <- as.numeric(signups$week - min(weeks)) / 7 k <- as.integer(signups$channel) signups$n <- round( (60 + 25 * sin(t / 6 + k)) * c(1.4, 1, 0.8, 0.5, 0.6)[k] + rpois(length(t), 6) ) streamgraph( data = signups, x = "week", group = "channel", value = "n", offset = "silhouette", x_format = "%b %Y", colors = c("#2caffe", "#544fc5", "#00e272", "#fe6a35", "#6b8abc"), legend = FALSE, title = "Weekly sign-ups by channel, 2026" )
A sunburst chart displays hierarchical data as concentric rings. The centre represents the whole, each ring is one level of the hierarchy, and every sector's angle is proportional to its value. The look and feel is inspired by the sunburst series of Apache ECharts, reimplemented here in plain D3.
The chart is interactive: hovering a sector highlights it together with its ancestors and shows a tooltip with its full path, value and shares; clicking a sector zooms into it (its children then fill the whole circle with a smooth arc transition) and clicking the centre zooms back out one level.
sunburst_chart( data, levels, value = NULL, colors = NULL, value_format = ",.0f", inner_radius = 0.22, corner_radius = 0, pad_angle = 0, stroke_col = "white", stroke_width = 1, show_labels = TRUE, label_rotate = c("radial", "tangential"), label_font_size = 11, label_col = NULL, root_label = "Total", center_font_size = 13, zoom = TRUE, hover = TRUE, animate = TRUE, duration = 750, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )sunburst_chart( data, levels, value = NULL, colors = NULL, value_format = ",.0f", inner_radius = 0.22, corner_radius = 0, pad_angle = 0, stroke_col = "white", stroke_width = 1, show_labels = TRUE, label_rotate = c("radial", "tangential"), label_font_size = 11, label_col = NULL, root_label = "Total", center_font_size = 13, zoom = TRUE, hover = TRUE, animate = TRUE, duration = 750, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
levels |
A character vector of column names that define the
hierarchy, from the outermost category (inner ring) to the most detailed
one (outer ring), e.g. |
value |
Optional. The name of a numeric (non-negative) column that
determines the size of each sector. Defaults to |
colors |
Optional. A vector of colors, one per first-level category
(recycled if needed). Deeper levels use progressively lighter shades of
their branch color. Defaults to |
value_format |
A d3-format specifier used to display values in the
centre and the tooltip (e.g. |
inner_radius |
Radius of the centre circle as a fraction of the
chart's radius, between |
corner_radius |
Corner radius of the sectors in pixels. Defaults to
|
pad_angle |
Angular padding between sectors in radians (e.g.
|
stroke_col |
Color of the sector borders. Defaults to |
stroke_width |
Width of the sector borders in pixels. Defaults to
|
show_labels |
Whether to display the sector labels. Labels are
truncated or hidden automatically when a sector is too small. Defaults to
|
label_rotate |
Orientation of the sector labels: |
label_font_size |
Font size of the sector labels. Defaults to
|
label_col |
Optional. Color of the sector labels. Defaults to
|
root_label |
Label shown in the centre (and used as the root name)
when the chart is not zoomed. Defaults to |
center_font_size |
Maximum font size of the centre label. Defaults to
|
zoom |
Whether clicking a sector zooms into it and clicking the centre
zooms out. Defaults to |
hover |
Whether to highlight the hovered sector (and its ancestors)
and show a tooltip. Defaults to |
animate |
Whether the sectors sweep in with an entrance animation.
Defaults to |
duration |
Duration of the zoom transition in milliseconds. Defaults
to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
text_col |
Color of the title and the centre label. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG sunburst chart.
# World population in 2007 by continent and country library(gapminder) pop_2007 <- gapminder[gapminder$year == 2007, ] sunburst_chart( data = pop_2007, levels = c("continent", "country"), value = "pop", value_format = ".3~s", root_label = "World", title = "World population in 2007" ) # A three-level hierarchy: a toy company's headcount staff <- data.frame( division = c(rep("Engineering", 6), rep("Sales", 4), rep("Operations", 4)), team = c("Platform", "Platform", "Data", "Data", "Mobile", "Mobile", "EMEA", "EMEA", "Americas", "APAC", "Finance", "Finance", "HR", "Legal"), role = c("Backend", "SRE", "Engineers", "Analysts", "iOS", "Android", "Account execs", "Sales engineers", "Account execs", "Account execs", "Accounting", "FP&A", "Recruiting", NA), people = c(42, 12, 18, 9, 11, 13, 25, 8, 31, 14, 10, 6, 9, 5) ) sunburst_chart( data = staff, levels = c("division", "team", "role"), value = "people", root_label = "Company", label_rotate = "tangential", pad_angle = 0.006, corner_radius = 3, title = "Headcount by division, team and role" ) # Without a value column, sectors are sized by row counts library(ggplot2) # for the mpg dataset sunburst_chart( data = mpg, levels = c("class", "manufacturer"), root_label = "Cars", title = "Number of car models by class and manufacturer" )# World population in 2007 by continent and country library(gapminder) pop_2007 <- gapminder[gapminder$year == 2007, ] sunburst_chart( data = pop_2007, levels = c("continent", "country"), value = "pop", value_format = ".3~s", root_label = "World", title = "World population in 2007" ) # A three-level hierarchy: a toy company's headcount staff <- data.frame( division = c(rep("Engineering", 6), rep("Sales", 4), rep("Operations", 4)), team = c("Platform", "Platform", "Data", "Data", "Mobile", "Mobile", "EMEA", "EMEA", "Americas", "APAC", "Finance", "Finance", "HR", "Legal"), role = c("Backend", "SRE", "Engineers", "Analysts", "iOS", "Android", "Account execs", "Sales engineers", "Account execs", "Account execs", "Accounting", "FP&A", "Recruiting", NA), people = c(42, 12, 18, 9, 11, 13, 25, 8, 31, 14, 10, 6, 9, 5) ) sunburst_chart( data = staff, levels = c("division", "team", "role"), value = "people", root_label = "Company", label_rotate = "tangential", pad_angle = 0.006, corner_radius = 3, title = "Headcount by division, team and role" ) # Without a value column, sectors are sized by row counts library(ggplot2) # for the mpg dataset sunburst_chart( data = mpg, levels = c("class", "manufacturer"), root_label = "Cars", title = "Number of car models by class and manufacturer" )
A treemap displays hierarchical (or flat) part-to-whole data as a set of
nested rectangles whose areas are proportional to a value. The technique
was invented by Ben Shneiderman in the early 1990s and was made famous by
SmartMoney's "Map of the Market" and by the New York Times' graphics of
the US federal budget and spending. When a group column is supplied
the chart becomes a two-level hierarchy: tiles are coloured by group and
each group gets its own header and border. Hovering over a tile highlights
it and shows a tooltip with its label, group, value and share of the total.
treemap_chart( data, value, label, group = NULL, tile = "squarify", padding = 2, colors = NULL, value_format = ",.0f", show_values = TRUE, label_font_size = 11, label_col = NULL, group_font_size = 12, stroke_col = "white", stroke_width = 1, hover = TRUE, legend = TRUE, legend_font_size = 11, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )treemap_chart( data, value, label, group = NULL, tile = "squarify", padding = 2, colors = NULL, value_format = ",.0f", show_values = TRUE, label_font_size = 11, label_col = NULL, group_font_size = 12, stroke_col = "white", stroke_width = 1, hover = TRUE, legend = TRUE, legend_font_size = 11, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
value |
The name of the numeric (non-negative) column that determines the area of each rectangle. |
label |
The name of the column used as the label of each rectangle (leaf). |
group |
Optional. The name of a categorical column used as the parent
category of each rectangle. When supplied, rectangles are nested inside
their group and coloured by group. Defaults to |
tile |
The tiling algorithm. One of |
padding |
Padding in pixels between rectangles (and around groups).
Defaults to |
colors |
Optional. A vector of colors. When |
value_format |
A d3-format specifier used to display values in the
labels and tooltip (e.g. |
show_values |
Whether to display the formatted value under each label.
Defaults to |
label_font_size |
Font size of the rectangle labels. Labels are
automatically truncated or hidden when a rectangle is too small to fit
them. Defaults to |
label_col |
Optional. Color of the rectangle labels. Defaults to
|
group_font_size |
Font size of the group headers (only used when
|
stroke_col |
Color of the rectangle borders. Defaults to
|
stroke_width |
Width of the rectangle borders in pixels. Defaults to
|
hover |
Whether to highlight the hovered rectangle and show a tooltip.
Defaults to |
legend |
Whether to display a legend of the groups (only used when
|
legend_font_size |
Font size of the legend text. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
text_col |
Color of the title and legend text. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG treemap chart.
# A toy government budget (in millions) by department and ministry budget <- data.frame( department = c("Hospitals", "Primary care", "Public health", "Schools", "Universities", "Vocational training", "Army", "Navy", "Air force", "Roads", "Railways", "Airports", "Pensions", "Unemployment", "Family benefits"), ministry = c("Health", "Health", "Health", "Education", "Education", "Education", "Defence", "Defence", "Defence", "Transport", "Transport", "Transport", "Social security", "Social security", "Social security"), spending = c(5200, 2100, 800, 3900, 1800, 600, 2300, 1400, 1700, 1500, 1100, 400, 7400, 1900, 1300) ) treemap_chart( data = budget, value = "spending", label = "department", group = "ministry", value_format = "$,.0f", title = "Where the money goes (millions)" ) # World population in 2007 by country, grouped by continent library(gapminder) pop_2007 <- gapminder[gapminder$year == 2007, ] treemap_chart( data = pop_2007, value = "pop", label = "country", group = "continent", value_format = ".3~s", padding = 1, title = "World population in 2007" )# A toy government budget (in millions) by department and ministry budget <- data.frame( department = c("Hospitals", "Primary care", "Public health", "Schools", "Universities", "Vocational training", "Army", "Navy", "Air force", "Roads", "Railways", "Airports", "Pensions", "Unemployment", "Family benefits"), ministry = c("Health", "Health", "Health", "Education", "Education", "Education", "Defence", "Defence", "Defence", "Transport", "Transport", "Transport", "Social security", "Social security", "Social security"), spending = c(5200, 2100, 800, 3900, 1800, 600, 2300, 1400, 1700, 1500, 1100, 400, 7400, 1900, 1300) ) treemap_chart( data = budget, value = "spending", label = "department", group = "ministry", value_format = "$,.0f", title = "Where the money goes (millions)" ) # World population in 2007 by country, grouped by continent library(gapminder) pop_2007 <- gapminder[gapminder$year == 2007, ] treemap_chart( data = pop_2007, value = "pop", label = "country", group = "continent", value_format = ".3~s", padding = 1, title = "World population in 2007" )
Draws one tile per item (countries, products, companies...) with an area proportional to its value, and animates the treemap through time: the tiles grow, shrink and reflow smoothly as the values change, items that enter fade and grow in from nothing, and leaving ones shrink away. Think "share of the world population" or "market capitalisation" through the years. A player at the bottom plays, pauses and scrubs the animation and a big period label sits in the top right corner.
treemap_race( data, label, value, time, group = NULL, tile = c("resquarify", "squarify", "binary", "slice", "dice", "sliceDice"), fill = NULL, color_category = NULL, color_by = c("group", "growth"), highlight = NULL, labels = TRUE, label_mode = c("value", "share", "growth"), padding = 2, max_label_size = 26, legend = NULL, agg = c("sum", "mean", "max", "min", "last"), fill_gaps = TRUE, frame_dur = 900, ease = "CubicInOut", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )treemap_race( data, label, value, time, group = NULL, tile = c("resquarify", "squarify", "binary", "slice", "dice", "sliceDice"), fill = NULL, color_category = NULL, color_by = c("group", "growth"), highlight = NULL, labels = TRUE, label_mode = c("value", "share", "growth"), padding = 2, max_label_size = 26, legend = NULL, agg = c("sum", "mean", "max", "min", "last"), fill_gaps = TRUE, frame_dur = 900, ease = "CubicInOut", autoplay = TRUE, loop = FALSE, controls = TRUE, start_frame = "first", time_format = NULL, title = NULL, title_font_size = 20, subtitle = NULL, subtitle_font_size = 13, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "#333333", value_format = NULL, value_prefix = "", value_suffix = "", tooltip = TRUE, width = NULL, height = NULL )
data |
The data frame containing the variables to consider (one row per item and period). |
label |
The name of the column giving the items (one tile per value). |
value |
The name of the numeric column giving the area of the tiles. Negative values cannot be drawn and are treated as missing. |
time |
The name of the column giving the periods: numeric (e.g.
years), |
group |
Optional. The name of a column grouping the items (e.g. the continent of each country). The treemap then has two levels: each group gets a frame, a header and a colour, and the legend can hide groups. |
tile |
The tiling algorithm: |
fill |
Optional. The colours of the tiles. With |
color_category |
Optional. The name of a D3 categorical colour scheme
(e.g. |
color_by |
How the tiles are coloured at first: |
highlight |
Optional. A character vector of items pinned from the start (outlined, the other tiles dimmed). |
labels |
Logical. Write the names and values in the tiles (labels that
do not fit are hidden, their font size follows the tile size). Defaults
to |
label_mode |
What the labels show under the names at first:
|
padding |
The space between tiles, in pixels. Defaults to 2. |
max_label_size |
The largest font size of the tile labels, in pixels. Defaults to 26. |
legend |
Logical. Show the legend of the groups. When |
agg |
How rows with the same item and period are combined:
|
fill_gaps |
Logical. Interpolate the value of an item between the
periods where it is known. Defaults to |
frame_dur |
The duration of one period, in milliseconds, at 1x speed. Defaults to 900. |
ease |
The easing used within each period, a d3-ease name such as
|
autoplay |
Logical. Start playing when the chart scrolls into view.
Defaults to |
loop |
Logical. Start again from the first period at the end.
Defaults to |
controls |
Logical. Show the player at the bottom and the label and
colour buttons at the top. Defaults to |
start_frame |
The period shown first: |
time_format |
Optional. A d3-time-format string used for dates, e.g.
|
title |
Optional. The title of the plot. |
title_font_size |
The font size of the plot title. Defaults to 20. |
subtitle |
Optional. A subtitle drawn under the title. |
subtitle_font_size |
The font size of the subtitle. Defaults to 13. |
font |
The font family to consider for all the text. Defaults to "Verdana, Geneva, Tahoma, sans-serif". |
bg_col |
The background colour of the SVG. Defaults to "white". |
axis_col |
The colour of the titles, headers and controls. Defaults to "#333333". |
value_format |
Optional. A d3-format string for the values, e.g.
|
value_prefix, value_suffix
|
Optional. Text added before or after every
value, e.g. |
tooltip |
Logical. Show a tooltip on hover. Defaults to |
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
The data is long: one row per item and period, with the item names in
label, the values in value and the periods in time
(numbers such as years, dates, or a factor or character column whose
levels give the order). Gaps inside an item are interpolated; items
missing before their first or after their last period enter and leave the
treemap. With group, the treemap has two levels (e.g. continent and
country): each group gets a frame and a header with its total, and its
tiles are drawn in shades of the group colour.
With the default tile = "resquarify", the layout keeps the same
rows of tiles while the values change, so the tiles glide instead of
jumping. When a row gets too stretched, the treemap is re-squarified, with
a short morph from the old layout to the new one.
An animated SVG treemap (an r2d3 htmlwidget).
The player at the bottom plays and pauses the animation (also with the space bar), the timeline can be dragged or clicked, the arrow keys step one period, Home and End jump to the start and the end. The speed button cycles from 0.5x to 4x, the loop button repeats the animation.
Hover a tile to see its value, its share of the total and of its group, its rank and its change since the previous period. The tooltip keeps updating while the animation plays. Hover a group header to see the group total and its largest items.
Click a group header to zoom into the group: its treemap fills the chart and keeps playing. Click "All" in the header (or press Escape) to zoom out.
Click a tile to pin it: it gets an outline and the other tiles are
dimmed. Click it again to unpin it. highlight pins items from
the start.
The buttons at the top switch the tile labels between the value, the share of the total and the growth since the previous period, and the colours between the palette and a growth heat map (red for items that shrink, green for items that grow).
With group, click a legend entry to hide or show a group
(the treemap is recomputed without it), double-click it to isolate it,
hover it to highlight its tiles.
Inside Shiny, with r2d3::d3Output("id") and r2d3::renderD3(),
clicking a tile sets input$id_clicked to a list with the
item, its group, value, share, period
and whether it is now pinned; input$id_zoom gives the group
zoomed into (NULL when zoomed out) and input$id_frame the
period shown (index and label). The current time, the speed,
the pinned items, the hidden groups, the zoom and the label and colour
modes are kept when the chart is re-rendered.
library(gapminder) # World population by country, grouped by continent treemap_race( gapminder, label = "country", value = "pop", time = "year", group = "continent", title = "World population", subtitle = "Click a continent header to zoom in", highlight = c("China", "India") ) # A few items, without groups, coloured by growth library(dplyr) # needed for data wrangling gapminder %>% filter(country %in% c("France", "Germany", "Italy", "Spain", "Poland")) %>% mutate(gdp = gdpPercap * pop / 1e9) %>% treemap_race( label = "country", value = "gdp", time = "year", color_by = "growth", label_mode = "share", value_prefix = "$", value_suffix = "B", value_format = ",.0f", title = "GDP of five European countries" )library(gapminder) # World population by country, grouped by continent treemap_race( gapminder, label = "country", value = "pop", time = "year", group = "continent", title = "World population", subtitle = "Click a continent header to zoom in", highlight = c("China", "India") ) # A few items, without groups, coloured by growth library(dplyr) # needed for data wrangling gapminder %>% filter(country %in% c("France", "Germany", "Italy", "Spain", "Poland")) %>% mutate(gdp = gdpPercap * pop / 1e9) %>% treemap_race( label = "country", value = "gdp", time = "year", color_by = "growth", label_mode = "share", value_prefix = "$", value_suffix = "B", value_format = ",.0f", title = "GDP of five European countries" )
A violin plot shows the distribution of a numeric variable for one or several groups. Each group is drawn as a mirrored kernel density estimate (the "violin"), so the width of the shape at a given value is proportional to how many observations lie around it. Violin plots reveal features that a box plot hides, such as multi-modality or skewness, while an inner box plot keeps the familiar summary statistics in view. The look and feel is inspired by the violin traces of the Plotly.js library.
The kernel density estimates are computed in the browser with a Gaussian
kernel. By default each violin gets its own bandwidth, computed with
Silverman's rule of thumb (equivalent to stats::bw.nrd0()).
The plot is interactive: hovering a violin dims the others, draws a horizontal spike line at the cursor (with its value tagged on the y-axis) and shows a tooltip with the group's summary statistics (n, min, q1, median, q3, max and mean). Hovering a raw point shows its value.
violin_plot( data, y, group = NULL, bandwidth = NULL, span = c("soft", "hard"), scale = c("width", "count"), box = TRUE, mean_line = FALSE, points = c("outliers", "all", "none"), jitter = 0.6, point_radius = 2.5, point_opacity = 0.7, sort = c("none", "mean", "median"), color_palette = "Category10", fill_opacity = 0.5, line_width = 1.5, violin_width = 0.8, hover = TRUE, animate = TRUE, y_title = NULL, y_title_font_size = 13, x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", grid_col = "#e6e6e6", width = NULL, height = NULL )violin_plot( data, y, group = NULL, bandwidth = NULL, span = c("soft", "hard"), scale = c("width", "count"), box = TRUE, mean_line = FALSE, points = c("outliers", "all", "none"), jitter = 0.6, point_radius = 2.5, point_opacity = 0.7, sort = c("none", "mean", "median"), color_palette = "Category10", fill_opacity = 0.5, line_width = 1.5, violin_width = 0.8, hover = TRUE, animate = TRUE, y_title = NULL, y_title_font_size = 13, x_title = NULL, x_title_font_size = 13, title = NULL, title_font_size = 16, x_font_size = 11, y_font_size = 11, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", grid_col = "#e6e6e6", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
y |
The name of the numeric column whose distribution is displayed. |
group |
Optional. The name of a categorical column used to split the
data into one violin per group. When the column is a factor, its level
order is used (unless |
bandwidth |
Optional. The kernel bandwidth, expressed as the standard
deviation of the Gaussian kernel (as in |
span |
How far the density extends. |
scale |
How the violin widths are scaled. |
box |
Logical. When |
mean_line |
Logical. When |
points |
Which raw observations to draw on top of the violins:
|
jitter |
Horizontal spread of the points, as a fraction (0 to 1) of
the violin's width at the point's value. Points therefore always stay
inside their violin. Defaults to |
point_radius |
Radius of the points in pixels. Defaults to |
point_opacity |
Fill opacity of the points (0 to 1). Defaults to
|
sort |
How to order the violins from left to right. One of
|
color_palette |
The violin colors. Either the name of a D3 categorical
color scheme (e.g. |
fill_opacity |
Fill opacity of the violins (0 to 1). Defaults to
|
line_width |
Width of the violin outline in pixels. Defaults to
|
violin_width |
Maximum width of a violin, as a fraction (0 to 1] of
the space allotted to each group. Defaults to |
hover |
Logical. When |
animate |
Logical. When |
y_title |
Optional. Title of the y-axis. |
y_title_font_size |
Font size of the y-axis title. Defaults to |
x_title |
Optional. Title of the x-axis. |
x_title_font_size |
Font size of the x-axis title. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
x_font_size |
Font size of the group labels. Defaults to |
y_font_size |
Font size of the y-axis tick labels. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of axis lines, ticks, and labels. Defaults to
|
grid_col |
Color of the horizontal grid lines. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG violin plot.
# Sepal length by species, with the inner box plot and outliers violin_plot( data = iris, y = "Sepal.Length", group = "Species", title = "Sepal length by species", y_title = "Sepal length (cm)" ) # Every observation jittered inside its violin, plus a mean line library(ggplot2) # for the mpg dataset violin_plot( data = mpg, y = "hwy", group = "class", points = "all", mean_line = TRUE, sort = "median", color_palette = "Tableau10", title = "Highway fuel economy by vehicle class", y_title = "Highway miles per gallon" ) # A bimodal distribution, width proportional to group size, hard span set.seed(2026) waiting <- data.frame( minutes = c(rnorm(300, 55, 6), rnorm(200, 80, 5), rnorm(150, 70, 10), rnorm(60, 62, 4)), station = rep(c("North", "Central", "South"), c(500, 150, 60)) ) violin_plot( data = waiting, y = "minutes", group = "station", scale = "count", span = "hard", color_palette = c(North = "#636efa", Central = "#ef553b", South = "#00cc96"), title = "Waiting time by station", y_title = "Minutes", x_title = "Station" ) # A single violin with a custom bandwidth violin_plot( data = faithful, y = "eruptions", bandwidth = 0.2, color_palette = "#9467bd", points = "all", y_title = "Eruption time (min)" )# Sepal length by species, with the inner box plot and outliers violin_plot( data = iris, y = "Sepal.Length", group = "Species", title = "Sepal length by species", y_title = "Sepal length (cm)" ) # Every observation jittered inside its violin, plus a mean line library(ggplot2) # for the mpg dataset violin_plot( data = mpg, y = "hwy", group = "class", points = "all", mean_line = TRUE, sort = "median", color_palette = "Tableau10", title = "Highway fuel economy by vehicle class", y_title = "Highway miles per gallon" ) # A bimodal distribution, width proportional to group size, hard span set.seed(2026) waiting <- data.frame( minutes = c(rnorm(300, 55, 6), rnorm(200, 80, 5), rnorm(150, 70, 10), rnorm(60, 62, 4)), station = rep(c("North", "Central", "South"), c(500, 150, 60)) ) violin_plot( data = waiting, y = "minutes", group = "station", scale = "count", span = "hard", color_palette = c(North = "#636efa", Central = "#ef553b", South = "#00cc96"), title = "Waiting time by station", y_title = "Minutes", x_title = "Station" ) # A single violin with a custom bandwidth violin_plot( data = faithful, y = "eruptions", bandwidth = 0.2, color_palette = "#9467bd", points = "all", y_title = "Eruption time (min)" )
A waffle chart is a grid of squares (by default 10 x 10 = 100 cells) in
which each category fills a number of cells proportional to its share of
the whole. Each cell therefore reads as "one percent" (or one unit of the
total), which makes part-to-whole comparisons far easier to read than a pie
chart. The format is a staple of Pew Research Center, FiveThirtyEight,
The Economist and the Washington Post, and was popularised in R by Bob
Rudis's waffle package.
Cells are allocated with the largest-remainder method, so the cell counts
always add up exactly to rows * cols. Unlike
parliament_chart, which draws individual seats along a
hemicycle, a waffle chart uses a rectangular grid to show proportions of a
whole rather than absolute counts.
waffle_chart( data, category, value, rows = 10, cols = 10, total = NULL, colors = NULL, empty_col = "#e5e5e5", cell_padding = 2, cell_radius = 2, direction = "row", legend = TRUE, legend_font_size = 12, hover = TRUE, animate = TRUE, animation_duration = 1200, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )waffle_chart( data, category, value, rows = 10, cols = 10, total = NULL, colors = NULL, empty_col = "#e5e5e5", cell_padding = 2, cell_radius = 2, direction = "row", legend = TRUE, legend_font_size = 12, hover = TRUE, animate = TRUE, animation_duration = 1200, title = NULL, title_font_size = 16, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", text_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. It should contain one row per category. |
category |
The name of the categorical column used as labels. |
value |
The name of the numeric (non-negative) column holding each category's value. |
rows |
Number of rows in the grid. Defaults to |
cols |
Number of columns in the grid. Defaults to |
total |
Optional. The value represented by the whole grid. Defaults to
the sum of |
colors |
Optional. A character vector of colors, one per category (recycled if shorter). Defaults to a Tableau-10 style palette. |
empty_col |
Color of the unfilled cells. Defaults to |
cell_padding |
Gap between cells in pixels. Defaults to |
cell_radius |
Corner radius of each cell in pixels. Defaults to
|
direction |
Fill direction. |
legend |
Whether to display a legend showing each category and its
percentage. Defaults to |
legend_font_size |
Font size of the legend text. Defaults to |
hover |
Whether hovering a cell or a legend entry highlights that
category and shows a label with its value and percentage. Defaults to
|
animate |
Whether the cells pop in sequentially when the chart loads.
Defaults to |
animation_duration |
Total duration of the load animation in
milliseconds. Defaults to |
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
text_col |
Color of the title and legend text. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An SVG waffle chart.
# How respondents answered a survey question survey <- data.frame( response = c("Strongly agree", "Agree", "Neutral", "Disagree", "Strongly disagree"), n = c(312, 405, 158, 87, 38) ) waffle_chart( data = survey, category = "response", value = "n", colors = c("#1a9641", "#a6d96a", "#bdbdbd", "#fdae61", "#d7191c"), title = "Do you support the new policy?" ) # Share of the world population by continent in 2007, filled by column library(gapminder) pop_2007 <- gapminder[gapminder$year == 2007, ] pop_continent <- aggregate(pop ~ continent, data = pop_2007, FUN = sum) waffle_chart( data = pop_continent, category = "continent", value = "pop", direction = "col", rows = 10, cols = 20, title = "World population by continent, 2007" )# How respondents answered a survey question survey <- data.frame( response = c("Strongly agree", "Agree", "Neutral", "Disagree", "Strongly disagree"), n = c(312, 405, 158, 87, 38) ) waffle_chart( data = survey, category = "response", value = "n", colors = c("#1a9641", "#a6d96a", "#bdbdbd", "#fdae61", "#d7191c"), title = "Do you support the new policy?" ) # Share of the world population by continent in 2007, filled by column library(gapminder) pop_2007 <- gapminder[gapminder$year == 2007, ] pop_continent <- aggregate(pop ~ continent, data = pop_2007, FUN = sum) waffle_chart( data = pop_continent, category = "continent", value = "pop", direction = "col", rows = 10, cols = 20, title = "World population by continent, 2007" )
A waterfall chart shows how an initial value is built up or eroded by a series of positive and negative contributions to reach a final total. Each bar starts exactly where the previous one ended, making cumulative effects immediately visible. It is the standard chart for P&L decomposition, budget variance analysis, and any "what changed and why" narrative.
Hovering over a bar shows a tooltip with the label, the delta value, and the running total at that point.
waterfall_chart( data, x, y, measure = NULL, positive_color = "#4CAF50", negative_color = "#F44336", total_color = "#5C85D6", connector = TRUE, connector_color = "#aaaaaa", show_labels = TRUE, label_font_size = 10, title = NULL, title_font_size = 16, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, x_font_size = 11, y_font_size = 11, opacity = 1, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )waterfall_chart( data, x, y, measure = NULL, positive_color = "#4CAF50", negative_color = "#F44336", total_color = "#5C85D6", connector = TRUE, connector_color = "#aaaaaa", show_labels = TRUE, label_font_size = 10, title = NULL, title_font_size = 16, x_title = NULL, x_title_font_size = 13, y_title = NULL, y_title_font_size = 13, x_font_size = 11, y_font_size = 11, opacity = 1, font = "Verdana, Geneva, Tahoma, sans-serif", bg_col = "white", axis_col = "black", width = NULL, height = NULL )
data |
The data frame containing the variables to consider. |
x |
The name of the column containing category labels. |
y |
The name of the column containing the delta values (positive for increases, negative for decreases). |
measure |
Optional. The name of a column that classifies each row as
|
positive_color |
Fill color for bars representing an increase.
Defaults to |
negative_color |
Fill color for bars representing a decrease.
Defaults to |
total_color |
Fill color for |
connector |
Logical. Whether to draw dashed connector lines between
consecutive bars. Defaults to |
connector_color |
Color of the connector lines. Defaults to
|
show_labels |
Logical. Whether to display the delta value above or
below each bar. Defaults to |
label_font_size |
Font size of the bar value labels. Defaults to
|
title |
Optional. Title of the chart. |
title_font_size |
Font size of the chart title. Defaults to |
x_title |
Optional. Title of the x-axis. |
x_title_font_size |
Font size of the x-axis title. Defaults to |
y_title |
Optional. Title of the y-axis. |
y_title_font_size |
Font size of the y-axis title. Defaults to |
x_font_size |
Font size of the x-axis tick labels. Defaults to |
y_font_size |
Font size of the y-axis tick labels. Defaults to |
opacity |
Opacity of the bars (0 to 1). Defaults to |
font |
The font family used for all text. Defaults to
|
bg_col |
Background color of the SVG. Defaults to |
axis_col |
Color of axis lines, ticks, and labels. Defaults to
|
width |
Optional. The width of the SVG output. |
height |
Optional. The height of the SVG output. |
An interactive SVG waterfall chart.
# P&L bridge: from revenue down to net income pnl <- data.frame( label = c("Revenue", "COGS", "Gross Profit", "R&D", "S&M", "G&A", "Operating Income"), value = c(1200, -450, 750, -120, -90, -60, 480), measure = c("relative", "relative", "total", "relative", "relative", "relative", "total") ) waterfall_chart( data = pnl, x = "label", y = "value", measure = "measure", title = "P&L bridge", y_title = "USD thousands" ) # Monthly cash flow cashflow <- data.frame( month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun"), delta = c(120, -30, 80, -60, 95, -20) ) waterfall_chart( data = cashflow, x = "month", y = "delta", title = "Monthly cash flow", y_title = "USD thousands", positive_color = "steelblue", negative_color = "tomato" )# P&L bridge: from revenue down to net income pnl <- data.frame( label = c("Revenue", "COGS", "Gross Profit", "R&D", "S&M", "G&A", "Operating Income"), value = c(1200, -450, 750, -120, -90, -60, 480), measure = c("relative", "relative", "total", "relative", "relative", "relative", "total") ) waterfall_chart( data = pnl, x = "label", y = "value", measure = "measure", title = "P&L bridge", y_title = "USD thousands" ) # Monthly cash flow cashflow <- data.frame( month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun"), delta = c(120, -30, 80, -60, 95, -20) ) waterfall_chart( data = cashflow, x = "month", y = "delta", title = "Monthly cash flow", y_title = "USD thousands", positive_color = "steelblue", negative_color = "tomato" )