Package 'ddplot'

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

Help Index


Create an animated line chart

Description

Create an animated line chart

Usage

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
)

Arguments

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.

Value

An animated SVG line chart.

Examples

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.

Description

Create an animated histogram.

Usage

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
)

Arguments

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.

Value

An animated SVG histogram.

Examples

animated_histogram(
 x = mtcars$mpg,
 duration = 2000,
 delay = 100
)

Create an interactive band chart

Description

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.

Usage

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"
)

Arguments

data

A data frame, or a ts / mts object.

x

The time variable: a Date, a POSIXct date-time, a "yyyy-mm-dd" character column or a number.

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 y, the outline defaults to a faded line in the band's colour.

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 FALSE.

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 transform = "none".

legend

Logical. Show the interactive legend (click to hide or show a series, double-click to isolate it). When NULL (default), the legend is shown when there are two series or more.

end_labels

Logical. Label each line at its last visible point. When NULL (default), labels are shown when there are two series or more.

tooltip

Logical. Show the crosshair and the tooltip on hover. Defaults to TRUE.

navigator

Logical. Show the navigator (a miniature of the full series with a brush to select the visible range) under the chart. Defaults to TRUE; it is hidden automatically on very short charts.

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 TRUE.

zoom

Logical. Drag horizontally on the chart to zoom into a range; double-click to reset. Defaults to TRUE.

animate

Logical. Draw the lines in with an animation on first render. Defaults to TRUE.

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 transform = "percent".

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 NULL (default), it is picked from the frequency of the data (yearly, quarterly, monthly, daily or intraday).

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".

Value

An interactive SVG band chart.

Examples

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"
)

Create an interactive area chart

Description

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.

Usage

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"
)

Arguments

data

A data frame, or a ts / mts object.

x

The time variable: a Date, a POSIXct date-time, a "yyyy-mm-dd" character column or a number. Not needed when data is a ts object.

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 NULL (default), the area is filled with a gradient that fades towards the axis.

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 baseline, the colour of the area (and line) below the baseline.

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 FALSE.

y_zero

Logical. Force the y axis to include 0. When NULL (default), it does unless baseline is given.

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 transform = "none".

legend

Logical. Show the interactive legend (click to hide or show a series, double-click to isolate it). When NULL (default), the legend is shown when there are two series or more.

end_labels

Logical. Label each line at its last visible point. When NULL (default), labels are shown when there are two series or more.

tooltip

Logical. Show the crosshair and the tooltip on hover. Defaults to TRUE.

navigator

Logical. Show the navigator (a miniature of the full series with a brush to select the visible range) under the chart. Defaults to TRUE; it is hidden automatically on very short charts.

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 TRUE.

zoom

Logical. Drag horizontally on the chart to zoom into a range; double-click to reset. Defaults to TRUE.

animate

Logical. Draw the lines in with an animation on first render. Defaults to TRUE.

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 transform = "percent".

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 NULL (default), it is picked from the frequency of the data (yearly, quarterly, monthly, daily or intraday).

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".

Details

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.

Value

An interactive SVG area chart.

Examples

# 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"
)

Create an interactive bar chart.

Description

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.

Usage

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"
)

Arguments

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 NULL, the rows of each category are counted.

fill

The colour of the bars. A single colour, or, without group, one colour per category (recycled; a named vector maps colours to categories). With group, one colour per group (a named vector maps colours to groups). Defaults to a built-in palette.

sort

The initial order of the bars: "none" (default, the order of the data or of the factor levels), "ascending" or "descending". With group, categories are sorted by their total.

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 (or "Count"); use "" to hide it.

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: "grouped" (default, side by side), "stacked" or "percent" (stacked to 100%). It can be changed from the chart when controls = TRUE.

agg

How rows with the same category (and group) are combined: "sum" (default), "mean", "median", "min", "max" or "count". With one row per bar, every option but "count" returns the value itself.

labels

Logical. Write the values on the bars (labels that do not fit are skipped). Defaults to TRUE.

highlight

Optional. A character vector of categories to emphasise; the other bars are drawn in grey (or faded, with group).

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 group).

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 NULL (default), it is shown when group is used.

controls

Logical. Show the layout and sort buttons. Defaults to TRUE.

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

animate

Logical. Animate the bars when the chart is first drawn. Defaults to TRUE.

value_format

Optional. A d3-format string for the values, e.g. ",.0f", ".1f" or "~s".

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " km".

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 NA to hide them.

Value

An interactive SVG bar chart (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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"
)

Create an animated, interactive bar chart race.

Description

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.

Usage

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"
)

Arguments

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), Date, POSIXct, or a factor or character column (factor levels, or the sorted values, give the order).

ease

The easing used within each period, a d3-ease name such as "Linear" (default, a steady race), "CubicInOut" (slows down on every period) or "BackInOut" (a little bounce). See <https://github.com/d3/d3-ease>.

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 frame_dur + transition_dur milliseconds at 1x speed: the bars rest for frame_dur, then move for transition_dur.

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. "Accent", "Tableau10", "Set2"), see <https://github.com/d3/d3-scale-chromatic#categorical>. When NULL (default), the ddplot palette is used. fill takes precedence.

sort

How the bars are ranked: "descending" (default, the largest value on top), "ascending" (the smallest value on top) or "none" (the bars keep the order of the data, or of the factor levels of y, and only the first top_n items are shown).

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 stroke is given).

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 NULL (default), a light grey, or white when panel_col is given. Use NA to hide them.

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 TRUE.

time_label_opts

A list of options for the period label: size (font size in pixels, chosen from the chart size when NULL), prefix and suffix (text around the period), xOffset and yOffset (shifts to the left and upwards, as a share of the width and height of the label, from the bottom right corner of the panel; both default to 0). Missing entries keep their defaults.

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 group), or a named vector mapping items (or groups) to colours, the others taking the palette.

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 TRUE.

name_position

Where the item names go: "left" (default, in a column left of the bars) or "inside" (inside the end of the bar, or just after it when the bar is too short).

total

Show the total of all the items under the period label, and the share of the total in the tooltip: FALSE (default), TRUE or a label such as "World". Only meaningful for values that add up.

rank_flash

Logical. Flash a small arrow next to a bar that overtakes another one. Defaults to TRUE.

agg

How rows with the same item and period are combined: "sum" (default), "mean", "max", "min" or "last".

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 TRUE.

autoplay

Logical. Start playing when the chart scrolls into view. Defaults to TRUE.

loop

Logical. Start again at the end. Defaults to FALSE; it can be toggled from the player.

start_frame

The period shown first: "first" (default), "last" or a period number.

time_format

Optional. A d3-time-format string for date periods, e.g. "%b %Y". Chosen from the spacing of the dates when NULL.

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. ",.0f", ".1f" or ".3~s".

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " years".

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

axis_col

The colour of the axes, labels and titles. Defaults to "#333333".

Details

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.

Value

An animated, interactive SVG bar chart race (an r2d3 htmlwidget).

Interactions

  • 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).

Shiny

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.

Examples

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"
)

Create a beeswarm plot.

Description

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.

Usage

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
)

Arguments

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 NULL (single swarm).

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 "column: value". When NULL (default) no tooltip is shown.

hover

Logical. When TRUE (default), hovering a point enlarges it and dims the rest of the swarm to make it stand out.

animate

Logical. When TRUE (default), points grow into place with a short staggered entry animation on first render.

stat

Character. Draws a reference line per swarm at the "mean" or "median" of the values. Defaults to "none" (no line).

stat_color

Color of the mean/median reference line and its label. Defaults to "#d62728".

col

Fill color of the points when no group is supplied. Defaults to "steelblue".

color_palette

D3 categorical color scheme used when group is supplied (e.g. "Tableau10", "Category10", "Set2"). Defaults to "Tableau10".

radius

Radius of each point in pixels. Defaults to 4.

opacity

Fill opacity of the points (0 to 1). Defaults to 0.75.

stroke

Stroke color of the points. Defaults to "white".

stroke_width

Stroke width in pixels. Defaults to 0.5.

x_title

Optional. Title of the x-axis.

x_title_font_size

Font size of the x-axis title. Defaults to 13.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

x_font_size

Font size of the x-axis tick labels. Defaults to 11.

y_font_size

Font size of the y-axis group labels. Defaults to 11.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of axis lines, ticks, and labels. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG beeswarm plot.

Examples

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"
)

Create a box plot

Description

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().

Usage

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
)

Arguments

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: "outliers" (the default), "all" (every observation, jittered over the box) or "none".

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: "none" (the default), "median" or "mean" (ascending).

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 y and the group axis with group.

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; NULL for none. Defaults to "#ececec".

width, height

Optional. The size of the chart.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

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"
)

Create an animated bubble chart race (Gapminder style).

Description

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.

Usage

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
)

Arguments

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 size_range[1] if larger).

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: "linear" (default) or "log". On a log scale, values that are not positive are dropped (with a warning). Both can be switched from the chart.

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 c(3, 40).

fill

Optional. The colours of the bubbles. With group, one colour per group (a named vector maps colours to groups). Without group, a single colour for every bubble, or one colour per item (recycled; a named vector maps colours to items). Defaults to a built-in palette.

color_category

Optional. The name of a D3 categorical colour scheme used instead of the built-in palette, e.g. "Tableau10", "Set2" or "Dark2". Ignored when fill is given.

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 FALSE.

labels

The number of bubbles labelled with their name: the largest ones (by size, or by y without size). Use 0 or FALSE for none and TRUE for all (labels that would overlap are skipped). Followed bubbles are always labelled; while some bubbles are followed, only they are labelled. Defaults to 5.

legend

Logical. Show the group legend. When NULL (default), it is shown when group is used.

size_legend

Logical. Show a legend of reference circles for size, drawn in the emptiest corner of the plot. Defaults to TRUE.

buttons

Logical. Show the buttons at the top right (log scales, trails, clear). Defaults to TRUE.

x_title, y_title

Optional. The titles of the axes. They default to the names of x and y; use "" to hide them.

size_title

Optional. The title of the size legend and the name of the size in the tooltip. Defaults to the name of size.

agg

How rows with the same item and period are combined: "mean" (default), "sum", "max", "min" or "last".

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 TRUE.

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: "Linear" (default, a smooth continuous motion), "CubicInOut" (a short pause at each period), "QuadInOut", ...

autoplay

Logical. Start playing when the chart scrolls into view. Defaults to TRUE.

loop

Logical. Start again at the end. It can be switched from the player. Defaults to FALSE.

controls

Logical. Show the player (play / pause, timeline, speed, loop) at the bottom. Defaults to TRUE.

start_frame

The first period shown: "first" (default), "last" or a period number (1 for the first one).

time_format

Optional. A d3-time-format string used for Date and POSIXct periods, e.g. "%b %Y". Chosen from the spacing of the periods by default.

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 NA to hide them.

value_format

Optional. A d3-format string for the values, e.g. ",.0f" or ".3s". A single string applies to x, y and size; a named vector sets them one by one, e.g. c(x = "$,.0f", y = ".1f").

value_prefix, value_suffix

Optional. Text added before or after the values, e.g. "$" or " years". As for value_format, a single string applies to every value and a named vector sets them one by one, e.g. value_prefix = c(x = "$").

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An animated, interactive SVG bubble chart (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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"
  )

Create a bullet chart.

Description

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.

Usage

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
)

Arguments

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. c(40, 70, 100)). The lower bound of the first band is min.

target

Optional numeric. The target / goal value shown as a short vertical marker. Defaults to NULL (no marker drawn).

range_colors

Character vector of colors for each band, in the same order as ranges. Defaults to a sequence of grays from darker (low range) to lighter (high range).

title

Character. Label displayed to the left of the chart. Defaults to "".

subtitle

Character. Smaller label displayed below title. Defaults to "".

min

Numeric. The minimum value of the scale. Defaults to 0.

value_color

The color of the actual-value bar. Defaults to "#1a1a2e".

target_color

The color of the target marker. Defaults to "#e63946".

tick_count

Number of axis ticks. Defaults to 5.

font_size

Base font size in pixels. Defaults to 12.

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".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG bullet chart.

Examples

# 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
)

Create a bump chart.

Description

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.

Usage

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
)

Arguments

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 ranked = TRUE).

group

The name of the column identifying each entity (one line per entity). Each group can appear at most once per period.

ranked

Whether y already contains ranks. Defaults to FALSE, in which case ranks are computed per period from y.

rank_order

How ranks are computed when ranked = FALSE. One of "desc" (default, the highest value gets rank 1) or "asc" (the lowest value gets rank 1). Ties are broken by order of appearance in the data.

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. "steelblue" or "#1f77b4"); R-only names such as "grey40" are not understood by the browser. Defaults to the D3 Tableau 10 palette.

highlight

Optional. A character vector of group names to highlight. All other groups are drawn in grey_col.

grey_col

Color used for groups that are not highlighted. Defaults to "#d3d3d3".

line_width

Width of the lines in pixels. Defaults to 3.

circle_radius

Maximum radius of the circles in pixels. It is reduced automatically when there are many groups or periods. Defaults to 11.

show_rank

Whether to print the rank number inside each circle. Defaults to TRUE.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

x_font_size

Font size of the period labels on the x-axis. Defaults to 11.

label_font_size

Font size of the group labels drawn at both ends of each line. Defaults to 11.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of the period labels, grid lines and title. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG bump chart.

Examples

# 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"
)

Create a calendar heatmap.

Description

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.

Usage

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
)

Arguments

data

The data frame containing the variables to consider.

date

The name of the column holding the dates. It can be of class Date, POSIXct or a character vector in "YYYY-MM-DD" format.

value

Optional. The name of the numeric column holding the value of each day. When NULL (default), the number of rows per day is used, which is handy for event logs (one row per event).

aggregate

How to combine several rows that share the same date. One of "sum" (default), "mean", "max", "min" or "count". Ignored (always "count") when value is NULL.

week_start

The first day of the week, i.e. the top row of the grid. Either "sunday" (default) or "monday".

colors

A vector of colors, from low to high, used to fill days that have a value. Values are split into length(colors) equal-width buckets. Defaults to a Frappe-like blue ramp c("#c0ddf9", "#73b3f3", "#3886e1", "#17459e").

empty_col

Fill color of days without data (or with a value of zero when all values are non-negative). Defaults to "#ebedf0".

cell_radius

Corner radius of the day squares in pixels. Defaults to 2.

cell_gap

Gap between day squares in pixels. Defaults to 3.

value_label

Optional. The unit shown after the value in the tooltip and year totals (e.g. "commits"). Defaults to the name of the value column, or "events" when value is NULL.

value_format

A d3-format specifier used to display values (e.g. ",.0f", "$,.2s"). Defaults to ",.2~f".

date_format

A d3-time-format specifier used to display dates in the tooltip. Defaults to "%a %b %-d, %Y" (e.g. "Wed Jan 7, 2026").

show_year_label

Whether to print the year and its total above each panel. Defaults to TRUE.

show_month_labels

Whether to print month labels above the grid. Defaults to TRUE.

show_weekday_labels

Whether to print weekday labels (Mon, Wed, Fri) on the left of the grid. Defaults to TRUE.

label_font_size

Font size of the month, weekday, year and legend labels. Defaults to 10.

legend

Whether to display the "Less ... More" legend. Defaults to TRUE.

legend_labels

A character vector of length 2 giving the text drawn on each side of the legend. Defaults to c("Less", "More").

hover

Whether to highlight the hovered day and show a tooltip. Defaults to TRUE.

animate

Whether the day squares fade in with a staggered animation on first render. Defaults to TRUE.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of the title and of the month, weekday, year and legend labels. Defaults to "#555555".

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.

Value

An SVG calendar heatmap.

Examples

# 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"
)

Create a candlestick chart

Description

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.

Usage

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
)

Arguments

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 c(20, 50).

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; NULL for none. Defaults to "#ececec".

width, height

Optional. The size of the chart.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

# 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")

Create a chord diagram.

Description

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.

Usage

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
)

Arguments

data

Either a data frame in edge-list format (one row per flow, with the columns named by from, to and value), or a square numeric matrix of flows with row and/or column names, where data[i, j] is the flow from entity i to entity j. Duplicated edges are summed. Self-flows (from == to) are allowed.

from

The name of the column holding the origin of each flow. Only used when data is a data frame. Defaults to "from".

to

The name of the column holding the destination of each flow. Only used when data is a data frame. Defaults to "to".

value

The name of the numeric (non-negative) column holding the size of each flow. Use NULL to count rows (every row counts as 1). Only used when data is a data frame. Defaults to "value".

directed

Whether flows are directed. When TRUE (default), A -> B and B -> A are kept apart, so a ribbon can be wider at one end than at the other. When FALSE, flows are treated as undirected links: in an edge list, both directions are summed; a symmetric matrix is used as is, and a non-symmetric one is symmetrized by adding its transpose (the diagonal is left unchanged).

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). Defaults to NULL.

color_palette

D3 categorical color scheme used when colors is NULL (e.g. "Tableau10", "Category10", "Set2", "Dark2", "Paired"). Defaults to "Tableau10".

ribbon_color

How ribbons are colored: "source" (default, the color of the entity with the larger outgoing flow of the pair), "target", or "gradient" (a gradient from one entity's color to the other's).

sort_groups

Order of the arcs around the circle: "none" (default, the order of first appearance in the edge list, the factor levels, or the matrix order), "descending" or "ascending" (by total flow).

pad_angle

Gap between adjacent arcs, in radians. Defaults to 0.03.

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 0.92.

arc_opacity

Fill opacity of the arcs (0 to 1). Defaults to 1.

ribbon_opacity

Fill opacity of the ribbons (0 to 1). Defaults to 0.6.

fade_opacity

Opacity of the ribbons and arcs that are faded out while another element is hovered (0 to 1). Defaults to 0.1.

stroke_width

Width of the arc and ribbon borders in pixels (the border uses a darker shade of the fill). Defaults to 0.5.

show_labels

Whether to display the entity names outside the arcs. Labels of arcs too small to hold them are hidden. Defaults to TRUE.

rotate_labels

Whether to orient the labels along the radius of the circle (useful with many entities). When FALSE (default), labels are horizontal.

label_font_size

Font size of the labels. Defaults to 11.

label_offset

Distance in pixels between the arcs and their labels. Defaults to 10.

value_format

A d3-format specifier used to display values in the tooltip (e.g. ",.0f", ".2s", "$,.1f"). Defaults to ",~f".

hover

Whether hovering highlights arcs and ribbons and shows a tooltip, and clicking an arc pins its highlight. Defaults to TRUE.

animate

Whether the arcs sweep in and the ribbons fade in on first render. Defaults to TRUE.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

text_col

Color of the title and the labels. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG chord diagram.

Examples

# 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"
)

Create a circle packing chart

Description

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.

Usage

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
)

Arguments

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 NULL, every row counts as 1.

group

Optional. The names of one or more columns giving the groups, from the outermost to the innermost, such as c("continent", "region").

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.

Value

An r2d3 htmlwidget.

Interactions

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).

Examples

# 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")

Create a density plot

Description

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().

Usage

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
)

Arguments

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 stats::density() ("nrd0", "nrd", "ucv", "bcv", "SJ"). Defaults to "nrd0".

adjust

A multiplier of the bandwidth: values above 1 give smoother curves. Defaults to 1.

position

"identity" (the default) draws the curves on top of each other, "stack" stacks them (each curve weighted by the size of its group) and "fill" shows the share of each group at every value.

stat

Optional reference lines per curve: "none" (the default), "mean" or "median".

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 x by default.

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; NULL for none. Defaults to "#ececec".

width, height

Optional. The size of the chart.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

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"
)

Create an animated donut race (a share race through time)

Description

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.

Usage

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
)

Arguments

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), Date, POSIXct, or a factor or character column (in the order of its levels, or alphabetical).

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: "value" (default, the ranking of each period, largest first; the slices slide past each other when the ranking changes) or "fixed" (the order of the data, or of the factor levels, so that each slice stays in place and only grows or shrinks). The table is always ranked.

max_slices

Optional. The maximum number of slices: in each period, the smallest items are grouped into an "Other" slice so that at most max_slices slices are drawn.

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 TRUE.

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 TRUE.

center_label

The caption under the total in the centre of the donut. Defaults to "Total"; FALSE hides the 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 fill is not given. Defaults to the ddplot palette.

highlight

Optional. A character vector of items pinned from the start.

agg

How rows with the same item and period are combined: "sum" (default), "mean", "max", "min" or "last".

fill_gaps

Logical. Interpolate the missing values of an item between two periods where it is known. Defaults to TRUE.

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 TRUE.

loop

Logical. Start again at the end. Defaults to FALSE (it can be switched in the player).

controls

Logical. Show the player (play button, timeline, speed and loop buttons). Defaults to TRUE.

start_frame

Where the animation starts: "first" (default), "last" or a period number (1 for the first).

time_format

Optional. A D3 time format for date periods, such as "%b %Y". Defaults to a format chosen from the spacing of the periods.

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 ",.0f" or ".2s".

value_prefix, value_suffix

Optional. Text added before and after the values, such as "$" or " TWh".

tooltip

Logical. Show a tooltip when hovering the slices and the rows. Defaults to TRUE.

width

Optional. The width of the chart.

height

Optional. The height of the chart.

Details

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.

Value

An interactive, animated SVG donut race (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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 = " %"
)

Create a dumbbell chart.

Description

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.

Usage

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
)

Arguments

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 x1.

x2_label

Legend label for the second value. Defaults to the value of x2.

col1

Color of the first dot. Defaults to "steelblue".

col2

Color of the second dot. Defaults to "crimson".

line_col

Color of the line connecting the two dots. Defaults to "#aaaaaa".

line_width

Width of the connecting line in pixels. Defaults to 2.

circle_radius

Radius of the dots in pixels. Defaults to 6.

sort

Whether to sort the rows. One of "none" (default), "ascending", or "descending", ordered by the x1 value.

x_title

Optional. Title of the x-axis.

x_title_font_size

Font size of the x-axis title. Defaults to 13.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

x_font_size

Font size of the x-axis tick labels. Defaults to 11.

y_font_size

Font size of the y-axis category labels. Defaults to 11.

legend

Whether to display a legend. Defaults to TRUE.

legend_font_size

Font size of the legend text. Defaults to 11.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of axis lines, ticks, and labels. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG dumbbell chart.

Examples

# 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"
)

Show an intensity as a flickering flame

Description

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.

Usage

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
)

Arguments

intensity

A non-negative number: the intensity of the flame. The height of the flame grows linearly with it up to max_intensity, where the flame reaches the top of the chart. Defaults to 50.

flame_gradient_colors

A length-3 character vector of colours, from the core of the flame outwards. Defaults to c("#fffbe6", "#ffc233", "#e8452c").

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 label_color.

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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.

Shiny

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.

Examples

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"
)

Draw a blooming flower, or a flower chart

Description

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".

Usage

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
)

Arguments

petal_count

The number of petals. Defaults to 6. Ignored when petal_values is given.

petal_length

Optional. The length of the petals (the longest one with petal_values) in pixels. By default the flower fills the space available.

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_values.

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 petal_values.

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 petal_values), written at their tips and in the tooltips.

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 petal_values.

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.

Details

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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).

Shiny

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.

Examples

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"
)

Create a funnel chart

Description

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.

Usage

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
)

Arguments

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

"funnel" (the default) joins the bars with a funnel shape; "bars" draws the bars alone.

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.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

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")

Create a Gantt chart

Description

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).

Usage

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
)

Arguments

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 TRUE for today's date.

sort

How to order the tasks: "none" (the order of the rows, the default), "start" (by start date) or "group" (by group, then by start date).

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.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

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")

Create a gauge (speedometer) chart.

Description

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.

Usage

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
)

Arguments

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 TRUE (default), the needle sweeps from the minimum up to the value on load and settles with a small wobble. Set to FALSE to draw the needle at the value immediately with no animation.

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.

Value

An SVG gauge chart.

Examples

# 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
)

Show a level as a glass filling with water

Description

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.

Usage

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
)

Arguments

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 NULL to hide it.

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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).

Shiny

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.

Examples

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")

Show a level as hair growing into a big afro

Description

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.

Usage

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
)

Arguments

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 NULL for no card.

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 NULL to hide it.

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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).

Shiny

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.

Examples

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"
)

Show a level as a beating heart filling with liquid

Description

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.

Usage

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
)

Arguments

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 NULL to hide it.

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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).

Shiny

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.

Examples

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")

Create a heatmap

Description

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.

Usage

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
)

Arguments

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 NULL, cells count the rows of each pair.

aggregate

How to combine several rows of the same pair: "sum" (the default), "mean", "median", "min" or "max".

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.

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 (stats::hclust()). Defaults to FALSE.

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.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

# 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)

Create a hexbin plot.

Description

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.

Usage

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
)

Arguments

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 12.

size_by_count

Logical. When TRUE, the area of each hexagon is also proportional to its count (the largest bin fills its cell), in addition to the fill color. Defaults to FALSE.

color_palette

The name of a D3 sequential color interpolator, without the "interpolate" prefix (e.g. "Viridis", "Blues", "YlGnBu", "Magma", "Turbo"). Defaults to "YlGnBu".

reverse_colors

Logical. Whether to reverse the direction of the color palette. Defaults to FALSE.

color_scale

How counts are mapped to colors: "linear" (default), "sqrt" or "log". Use "sqrt" or "log" when a few very dense bins wash out the rest.

legend

Logical. Whether to draw the continuous color legend. Defaults to TRUE.

legend_title

Title of the color legend. Defaults to "Count".

tooltip

Logical. Whether to show a tooltip when a hexagon is hovered. Defaults to TRUE.

hover

Logical. When TRUE (default), hovering a hexagon outlines it and marks its count on the legend.

animate

Logical. When TRUE (default), hexagons grow into place with a short staggered entry animation on first render.

opacity

Fill opacity of the hexagons (0 to 1). Defaults to 1.

stroke

Stroke color of the hexagons. Defaults to "white".

stroke_width

Stroke width of the hexagons in pixels. Defaults to 0.5.

grid

Logical. Whether to draw light gridlines behind the hexagons. Defaults to TRUE.

grid_col

Color of the gridlines. Defaults to "#e5e5e5".

x_title

Optional. Title of the x-axis. Defaults to the value of x.

y_title

Optional. Title of the y-axis. Defaults to the value of y.

x_title_font_size

Font size of the x-axis title. Defaults to 13.

y_title_font_size

Font size of the y-axis title. Defaults to 13.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

x_font_size

Font size of the x-axis tick labels. Defaults to 11.

y_font_size

Font size of the y-axis tick labels. Defaults to 11.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of axis lines, ticks, labels and titles. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG hexbin plot.

Examples

# 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"
)

Create an interactive histogram.

Description

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.

Usage

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"
)

Arguments

x

A numeric vector, or, when data is given, the name of a numeric column of data.

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 bin_width or breaks is given.

fill

The colour of the bars. A single colour, or, with group, one colour per group (a named vector maps colours to groups). Defaults to a built-in palette.

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 "" to hide it.

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 "" to hide it.

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; x and group are then column names.

group

Optional. A vector of the same length as x (or, with data, the name of a column) splitting the observations into groups, with one colour per group and a clickable legend.

bin_width

Optional. The width of the bins, in the units of x.

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: "stacked" (default) or "overlay" (semi-transparent bars drawn on top of each other). It can be changed from the chart when controls = TRUE.

stat

What the bar heights show: "count" (default), "percent" (share of the observations) or "density" (so that the areas of the bars add up to 1). Overlaid groups are each normalised by their own number of observations, so groups of different sizes can be compared.

density

Add a density curve: TRUE or "kde" for a kernel density estimate (Gaussian kernel, bandwidth from stats::bw.nrd0()), "normal" for the normal distribution with the mean and standard deviation of the data. The curve is scaled to the bars. With overlaid groups, one curve is drawn per group. Defaults to FALSE.

stats

Optional. Summary lines to draw across the bars: any of "mean" and "median" (TRUE draws both). With overlaid groups, one line is drawn per group.

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 FALSE.

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 TRUE.

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 group). Defaults to TRUE when there is a group.

controls

Logical. Show the buttons that change the bins, the counts / percentages and the layout. Defaults to TRUE.

tooltip

Logical. Show a tooltip when hovering the bins. Defaults to TRUE.

animate

Logical. Grow the bars when the chart is first drawn. Defaults to TRUE.

x_format

Optional. A D3 format string for the values of x (axis, tooltip and summary), such as ",.0f" or ".1f".

x_prefix, x_suffix

Optional. Text added before and after the values of x, such as "$" or " km".

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 NA to hide them.

Value

An interactive SVG histogram (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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"
)

Create an interactive horizontal bar chart

Description

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.

Usage

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"
)

Arguments

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 NULL, the rows of each category are counted.

fill

The colour of the bars. A single colour, or, without group, one colour per category (recycled; a named vector maps colours to categories). With group, one colour per group (a named vector maps colours to groups). Defaults to a built-in palette.

sort

The initial order of the bars: "none" (default, the order of the data or of the factor levels), "ascending" or "descending". Descending puts the largest bar at the top.

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 (or "Count"); use "" to hide it.

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: "grouped" (default, side by side), "stacked" or "percent" (stacked to 100%). It can be changed from the chart when controls = TRUE.

agg

How rows with the same category (and group) are combined: "sum" (default), "mean", "median", "min", "max" or "count". With one row per bar, every option but "count" returns the value itself.

labels

Logical. Write the values on the bars (labels that do not fit are skipped). Defaults to TRUE.

highlight

Optional. A character vector of categories to emphasise; the other bars are drawn in grey (or faded, with group).

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 group).

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 NULL (default), it is shown when group is used.

controls

Logical. Show the layout and sort buttons. Defaults to TRUE.

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

animate

Logical. Animate the bars when the chart is first drawn. Defaults to TRUE.

value_format

Optional. A d3-format string for the values, e.g. ",.0f", ".1f" or "~s".

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " km".

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 NA to hide them.

Value

An interactive SVG horizontal bar chart (an r2d3 htmlwidget).

Examples

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"
)

Create an interactive horizontal lollipop chart

Description

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.

Usage

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
)

Arguments

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 NULL, the rows of each category are counted.

sort

The initial order of the lollipops: "none" (default, the order of the data or of the factor levels), "ascending" or "descending". Descending puts the largest value at the top.

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 (or "Count"); use "" to hide it.

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 group, one colour per category (recycled; a named vector maps colours to categories). With group, one colour per group (a named vector maps colours to groups). Defaults to a built-in palette.

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: "sum" (default), "mean", "median", "min", "max" or "count". With one row per bar, every option but "count" returns the value itself.

labels

Logical. Write the values next to the dots (when every label fits). Defaults to TRUE.

highlight

Optional. A character vector of categories to emphasise; the other lollipops are drawn in grey (or faded, with group).

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 group).

legend

Logical. Show the legend. When NULL (default), it is shown when group is used.

controls

Logical. Show the sort buttons. Defaults to TRUE.

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

animate

Logical. Animate the lollipops when the chart is first drawn. Defaults to TRUE.

value_format

Optional. A d3-format string for the values, e.g. ",.0f", ".1f" or "~s".

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " km".

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 NA to hide them.

opacity

The opacity of the lollipops (from 0 to 1). Defaults to 1.

Value

An interactive SVG horizontal lollipop chart (an r2d3 htmlwidget).

Examples

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"
)

Create a Likert chart

Description

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.

Usage

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
)

Arguments

data

A data frame, with one row per answer (or one row per question and answer with a value column of counts).

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 NULL, each row counts as one answer.

levels

Optional. The answers in order, from the most negative to the most positive. Defaults to the factor levels of response, or to the order of appearance.

colors

Optional. One colour per level. By default a red - grey - blue scale.

sort

How to order the questions: "none" (the default), "positive" (the most positive at the top) or "negative".

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.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

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"))

Create an interactive time series line chart

Description

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.

Usage

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
)

Arguments

data

A data frame, or a ts / mts object.

x

The time variable. Can be a Date, a POSIXct date-time, a character column in "yyyy-mm-dd" format, or a numeric column (for example years). Not needed when data is a ts object.

y

The value variable(s). One column name, or several column names to draw one line per column (wide data). For a univariate ts object, it is the name given to the series (defaults to "value").

group

Optional. For long data, the column whose values name the series (one line per value). Cannot be combined with several y columns.

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 y columns, give one column per y column (use NA for series without a ribbon).

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 NULL (default), the first palette color is used.

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 FALSE.

points

Logical. Draw a marker on every data point. Defaults to FALSE.

y_scale

Either "linear" (default) or "log".

y_zero

Logical. Force the y axis to include 0. When NULL (default), 0 is included only when area = TRUE; otherwise the axis fits the data in view.

transform

How values are displayed: "none" (default), "index" (each series rebased to index_base at the first visible date, so series on different scales can be compared) or "percent" (change since the first visible date). The base moves with the zoom.

index_base

The value series are rebased to when transform = "index". Defaults to 100.

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 roll_mean is used, also draw the raw series as a thin faded line. Defaults to TRUE.

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 transform = "none".

legend

Logical. Show the interactive legend (click to hide or show a series, double-click to isolate it). When NULL (default), the legend is shown when there are two series or more.

end_labels

Logical. Label each line at its last visible point. When NULL (default), labels are shown when there are two series or more.

tooltip

Logical. Show the crosshair and the tooltip on hover. Defaults to TRUE.

navigator

Logical. Show the navigator (a miniature of the full series with a brush to select the visible range) under the chart. Defaults to TRUE; it is hidden automatically on very short charts.

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 TRUE.

zoom

Logical. Drag horizontally on the chart to zoom into a range; double-click to reset. Defaults to TRUE.

animate

Logical. Draw the lines in with an animation on first render. Defaults to TRUE.

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 transform = "percent".

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 NULL (default), it is picked from the frequency of the data (yearly, quarterly, monthly, daily or intraday).

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.

Details

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.

Value

An interactive SVG line chart.

Examples

# 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"
)

Create a racing line chart.

Description

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.

Usage

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
)

Arguments

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), Date, POSIXct, or a character or factor column of ordered periods.

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: "value" (default) or "rank" (a bump chart race, rank 1 at the top). It can be changed from the chart when controls = TRUE.

top_n

Optional. A number of lines: only the current top top_n lines are coloured and labelled, the others are drawn as thin grey lines in the background. The set changes as the race goes. In rank mode, the vertical axis shows the first top_n ranks.

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). Defaults to a built-in palette.

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 fill is not given. Defaults to the ddplot palette.

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: "linear" (default) or "log" (values that are not positive are dropped).

y_zero

Logical. Start the value axis at zero (linear scale only). Defaults to TRUE; use FALSE to zoom on the range of the values seen so far.

window

Optional. A number of periods: the time axis then slides to show only the last window periods.

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 window. Defaults to FALSE.

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. c("Oil crisis" = 1973)), or a data frame whose first column holds the times and second column the labels. Times use the type of the x column (numbers, dates or period labels).

labels

Logical. Show the name and the live value next to the head of each line. Defaults to TRUE.

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 TRUE.

agg

How rows with the same line and period are combined: "sum" (default), "mean", "max", "min" or "last".

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 y; use "" to hide it.

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 ease prefix, e.g. "Linear" (default, a constant speed) or "CubicInOut".

autoplay

Logical. Start playing when the chart scrolls into view. Defaults to TRUE.

loop

Logical. Start again at the end. Defaults to FALSE; it can be changed from the player.

controls

Logical. Show the player and the mode buttons. Defaults to TRUE.

start_frame

The period shown first: "first" (default), "last" (the full lines) or a period number.

time_format

Optional. A d3 time format for date periods, e.g. "%b %Y".

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 NA to hide them.

value_format

Optional. A d3-format string for the values, e.g. ",.0f", ".1f" or "~s".

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " years".

tooltip

Logical. Show tooltips on hover. Defaults to TRUE.

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Details

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).

Value

An interactive SVG racing line chart (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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")

Create a liquid fill gauge chart.

Description

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.

Usage

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
)

Arguments

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 value formatted as a percentage (e.g. "55%").

fill_color

The color of the liquid. Defaults to "steelblue".

circle_color

The color of the outer ring. Defaults to fill_color.

circle_thickness

Thickness of the outer ring as a fraction of the circle radius. Defaults to 0.05.

text_color

Color of the label text above the water surface. Defaults to fill_color.

wave_text_color

Color of the label text below (inside) the water surface. Defaults to "white".

text_size

Font size of the label as a fraction of the circle radius. Defaults to 0.38.

wave_amplitude

Height of the wave as a fraction of the circle radius. Defaults to 0.09.

wave_count

Number of full wave cycles visible across the circle. Defaults to 2.

wave_speed

Speed of the horizontal wave animation. Higher values are faster. Defaults to 1.

title

Optional. A label displayed below the circle.

title_font_size

Font size of the title in pixels. Defaults to 14.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An animated SVG liquid fill gauge.

Examples

# 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"
)

Create an interactive lollipop chart

Description

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.

Usage

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
)

Arguments

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 NULL, the rows of each category are counted.

sort

The initial order of the lollipops: "none" (default, the order of the data or of the factor levels), "ascending" or "descending". With group, categories are sorted by their total.

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 (or "Count"); use "" to hide it.

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 group, one colour per category (recycled; a named vector maps colours to categories). With group, one colour per group (a named vector maps colours to groups). Defaults to a built-in palette.

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: "sum" (default), "mean", "median", "min", "max" or "count". With one row per bar, every option but "count" returns the value itself.

labels

Logical. Write the values next to the dots (when every label fits). Defaults to TRUE.

highlight

Optional. A character vector of categories to emphasise; the other lollipops are drawn in grey (or faded, with group).

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 group).

legend

Logical. Show the legend. When NULL (default), it is shown when group is used.

controls

Logical. Show the sort buttons. Defaults to TRUE.

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

animate

Logical. Animate the lollipops when the chart is first drawn. Defaults to TRUE.

value_format

Optional. A d3-format string for the values, e.g. ",.0f", ".1f" or "~s".

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " km".

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 NA to hide them.

opacity

The opacity of the lollipops (from 0 to 1). Defaults to 1.

Value

An interactive SVG lollipop chart (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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"
)

Create a mosaic (Marimekko) chart.

Description

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.

Usage

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
)

Arguments

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 x/fill combination. Defaults to NULL, which counts rows instead.

colors

Optional. A vector of colors, one per fill category, recycled if needed. Defaults to NULL, which uses D3's Tableau 10 palette.

gap

Width in pixels of the white gaps between columns and between segments. Defaults to 2.

label_type

What to print inside each cell when there is room for it: "percent" (the share within the column, the default), "count" (the count or summed value), "both", or "none".

value_format

A d3-format specifier used to display counts or values in the labels and the tooltip (e.g. ",.0f", ".3~s"). Defaults to ",.0f".

label_font_size

Font size of the in-cell labels. Defaults to 11.

label_col

Optional. Color of the in-cell labels. Defaults to NULL, which picks white or near-black automatically for contrast with each cell's fill.

column_font_size

Font size of the column (x category) labels drawn above the chart. Labels that do not fit their column are shortened or hidden. Defaults to 12.

hover

Whether to highlight the hovered cell and show a tooltip. Defaults to TRUE.

animate

Whether the columns grow into place with a short staggered animation on first render. Defaults to TRUE.

legend

Whether to display a legend of the fill categories. Defaults to TRUE.

legend_title

Optional. Title of the legend. Defaults to NULL, which uses the name of the fill column. Use "" to hide it.

legend_font_size

Font size of the legend text. Defaults to 11.

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 12.

x_font_size

Font size of the x-axis tick labels. Defaults to 10.

y_font_size

Font size of the y-axis tick labels. Defaults to 10.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. It is also the color of the gaps between cells. Defaults to "white".

axis_col

Color of the axes, the axis labels, the column labels, the legend text and the title. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG mosaic chart.

Examples

# 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"
)

Show a level as a sailor's biceps growing bigger and bigger

Description

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.

Usage

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
)

Arguments

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 NULL for no card.

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 NULL to hide it.

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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).

Shiny

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.

Examples

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"
)

Create a network graph

Description

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).

Usage

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
)

Arguments

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 nodes that holds the node ids (the values used in from and to). Defaults to its first column.

node_group, node_size, node_label

Optional. Names of columns of nodes giving the group (colour), the size (a number) and the label of each node.

directed

Logical. Draw arrows from from to to. Defaults to FALSE.

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 c(5, 18).

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.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

# 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)

Show a level as a nose that grows longer and longer

Description

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.

Usage

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
)

Arguments

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 NULL for no card.

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 NULL to hide it.

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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).

Shiny

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.

Examples

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"
)

Create an interactive parliament chart

Description

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.

Usage

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"
)

Arguments

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 c(Greens = "#3ca951")); the other parties get the ddplot palette.

color_category

Optional. The name of a D3 categorical colour scheme, such as "Tableau10" or "Set2", used when fill is not given.

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: TRUE (default) for more than half of the seats, a number of seats, a share of the seats (a number below 1, such as 2/3, rounded up), or FALSE to draw no majority line.

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 TRUE.

regroup

Logical. Move the seats of the coalition to the left of the hemicycle. Defaults to TRUE.

sort

The order of the parties from left to right: "none" (default, the order of the data or of the factor levels, as parties are usually ordered by political orientation), "descending" (largest first) or "ascending".

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: "circle" (default) or "square".

center_label

The text under the number of seats in the centre. Defaults to "seats"; FALSE leaves the centre empty.

legend

Logical. Show the legend, with the seats and shares (on the right when there is room, otherwise below). Defaults to TRUE.

tooltip

Logical. Show a tooltip when hovering the seats. Defaults to TRUE.

animate

Logical. Fill the seats from left to right when the chart comes into view. Defaults to TRUE.

axis_col

The colour of the texts. Defaults to "#333333".

Details

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.

Value

An interactive parliament chart (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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"
)

Create an interactive pie or donut chart

Description

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.

Usage

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"
)

Arguments

data

The data frame to consider.

value

The name of the numeric variable (the size of the slices). When NULL, the rows of each label are counted. Rows with the same label are added up; negative and missing values are left out.

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 fill is not given. Defaults to the ddplot palette.

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 font.

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: "descending" (default, largest first), "ascending" or "none" (the order of the data, or of the factor levels).

max_slices

Optional. The maximum number of slices: the smallest categories are combined into an "Other" slice so that at most max_slices slices are drawn.

other_label

The label of the combined slice. Defaults to "Other".

labels

What to write for each slice: any of "label", "value" and "percent", or "none". Defaults to "percent" with a legend, c("label", "percent") without.

label_position

Where the slice labels go: "auto" (default, inside the slices that are large enough, outside with a leader line for the others), "inside" or "outside".

legend

Logical. Show the legend (on the right when there is room, otherwise below). Defaults to TRUE.

center_label

For a donut chart, the text shown under the total in the centre: NULL (default, "Total"), a string, or FALSE to leave the centre empty.

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 pad_angle is given).

tooltip

Logical. Show a tooltip when hovering the slices. Defaults to TRUE.

animate

Logical. Sweep the slices in when the chart is first drawn. Defaults to TRUE.

value_format

Optional. A D3 format string for the values, such as ",.0f" or ".2s".

value_prefix, value_suffix

Optional. Text added before and after the values, such as "$" or " kg".

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".

Value

An interactive SVG pie chart (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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
)

Show progress as a growing plant

Description

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.

Usage

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
)

Arguments

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 pot_color.

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 NULL to hide it.

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.

Value

An r2d3 htmlwidget.

Interactions

  • 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).

Shiny

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.

Examples

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
)

Create a pulse grid.

Description

'pulse_grid()' creates a tiled grid where each cell color reflects a numeric value and the cells gently pulse according to their intensity.

Usage

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
)

Arguments

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.

Value

A SVG pulse grid.

Examples

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"
)

Create a radar chart.

Description

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.

Usage

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
)

Arguments

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 NULL, which uses every numeric column except group.

axis_labels

Optional. A character vector, the same length as axes, of labels displayed at the end of each spoke. Defaults to the column names.

max_value

Optional. The value of the outer ring. With a shared scale, a single positive number; with scale_each_axis = TRUE, either a single number or one number per axis. Defaults to NULL, which rounds the data maximum up to a "nice" value. Values above max_value are drawn on the outer ring.

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 FALSE (one scale shared by all axes).

levels

The number of concentric grid rings. Defaults to 5.

grid_shape

Shape of the grid rings, either "polygon" (default) or "circle".

colors

Optional. A vector of colors, one per series (recycled if shorter). Defaults to NULL, which uses a soft palette in the spirit of Chart.js.

fill_opacity

Opacity of the polygon fills, between 0 and 1. Defaults to 0.2.

line_width

Width of the polygon outlines in pixels. Defaults to 2.

point_radius

Radius of the point markers in pixels. Defaults to 3. Use 0 to hide the markers.

show_ticks

Whether to print the value of each grid ring along the top spoke (shared scale only). Defaults to TRUE.

value_format

A d3-format specifier used to display values in the ticks and the tooltip, e.g. ".1f" or ".0%". Defaults to "," (thousands separator, insignificant zeros trimmed).

grid_col

Color of the grid rings and spokes. Defaults to "#dddddd".

hover

Whether to show a tooltip and highlight the hovered series. Defaults to TRUE.

animate

Whether the polygons grow out from the center on first render. Defaults to TRUE.

legend

Whether to display a clickable legend of the series. Defaults to TRUE.

legend_font_size

Font size of the legend text. Defaults to 12.

label_font_size

Font size of the axis labels. Defaults to 12.

tick_font_size

Font size of the grid ring tick labels. Defaults to 10.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of the axis labels, tick labels, legend text and title. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG radar chart.

Examples

# 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"
)

Create a radial bar chart.

Description

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.

Usage

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
)

Arguments

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 max are capped at a full sweep (with a warning). Defaults to 100.

start_angle

Angle in degrees at which every track starts, measured clockwise from 12 o'clock. Defaults to 0.

end_angle

Angle in degrees at which every track ends. Must be greater than start_angle and at most start_angle + 360. Defaults to 270.

colors

Optional. A vector of colors, one per ring (recycled if shorter). Defaults to NULL, which uses a built-in palette.

track_col

Color of the background tracks. Defaults to "#ececec".

hollow

Size of the empty center as a fraction (0 to 0.9) of the outer radius. Defaults to 0.35.

ring_gap

Fraction (0 to 0.9) of each ring's band left empty between neighbouring tracks. Defaults to 0.3.

rounded_caps

Whether the arcs (and partial tracks) have rounded ends. Defaults to TRUE.

show_labels

Whether to label each ring at the start of its track. Defaults to TRUE.

show_values

Whether to append the formatted value to each ring label (e.g. "Vimeo: 76%"). Defaults to TRUE.

label_font_size

Font size of the ring labels. Defaults to 12.

center_value

What to show in the center when nothing is hovered: "average" (default), "total" or "none".

center_label

Optional. Text shown above the center value. Defaults to "Average" or "Total" depending on center_value.

center_font_size

Optional. Font size of the big center value. Defaults to NULL, which sizes it to fit the hollow.

value_format

A d3-format specifier used to display values. Defaults to ",.0f".

suffix

Optional. Text appended to every displayed value. Defaults to NULL, which uses "%" when max = 100 and nothing otherwise.

hover

Whether hovering a ring highlights it, updates the center text and shows a tooltip. Defaults to TRUE.

animate

Whether the arcs sweep in on first render. Defaults to TRUE.

duration

Duration of the sweep animation in milliseconds. Defaults to 1200.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

text_col

Color of the title, labels and center text. Defaults to "#333333".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG radial bar chart.

Examples

# 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"
)

Create an animated radial bar chart race

Description

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.

Usage

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
)

Arguments

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 (Date or POSIXct), or a character or factor column (in the order of the factor levels, or sorted).

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: "spokes" (default, bars radiating from the centre) or "rings" (concentric arcs, best with top_n up to about 12). It can be changed from the chart.

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: "linear" (default, the length from the inner circle is proportional to the value) or "area" (the area of each spoke is proportional to the value).

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: "sum" (default), "mean", "max", "min" or "last".

fill_gaps

Logical. Interpolate the values of an item between the periods where it is known. Defaults to TRUE.

fill

Optional. The colours: a single colour, a vector of colours (recycled), or a named vector mapping colours to items (or to groups, with group). Defaults to the ddplot palette.

color_category

Optional. The name of a D3 categorical colour scheme, such as "Tableau10", "Set2" or "Paired", used when fill is not given.

highlight

Optional. A character vector of items to pin from the start.

center_value

What the centre shows under the period: "total" (default, the total of the items on show), "average" (their average, better for rates such as a life expectancy) or "none".

legend

Logical. Show the legend of the groups. When NULL (default), it is shown when group is used.

layout_buttons

Logical. Show the Spokes / Rings buttons. Defaults to TRUE.

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. "CubicInOut" (default), "Linear" or "QuadInOut".

autoplay

Logical. Start playing when the chart scrolls into view. Defaults to TRUE.

loop

Logical. Start again at the end. Defaults to FALSE; it can be toggled from the player.

controls

Logical. Show the player (play / pause, timeline, speed, loop). Defaults to TRUE.

start_frame

The period shown first: "first" (default), "last" or a period number (1 for the first).

time_format

Optional. A d3-time-format string for date periods, e.g. "%b %Y".

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. ",.0f", ".1f" or "~s".

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " km".

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

width

Optional. The width of the chart.

height

Optional. The height of the chart.

Value

An animated radial bar chart race (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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)

Create a ridgeline plot (joy plot).

Description

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.

Usage

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
)

Arguments

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 sort is set).

bandwidth

Optional. The kernel bandwidth, expressed as the standard deviation of the kernel (as in stats::density()). When NULL (default), a single joint bandwidth is computed from the pooled data with Silverman's rule of thumb (equivalent to stats::bw.nrd0()), so that all ridges are smoothed identically and remain comparable.

kernel

The smoothing kernel, either "gaussian" (default) or "epanechnikov".

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 overlap baselines up. Defaults to 1.5; use 1 for ridges that just touch and larger values for a more dramatic, Joy Division-like look.

fill

Fill color of the ridges. Either a single color (default "steelblue") applied to every ridge, an unnamed vector of colors recycled over the groups (in their original order), or a named vector whose names match the group values.

fill_opacity

Fill opacity of the ridges (0 to 1). Defaults to 0.8.

line_col

Color of the density outline. Defaults to "#333333".

line_width

Width of the density outline in pixels. Defaults to 1.

sort

How to order the ridges from top to bottom. One of "none" (default, factor level order or order of appearance), "mean", or "median". When sorting, the group with the smallest mean/median is placed at the top.

stat

Character. Draws a vertical line inside each ridge at the "mean" or "median" of its values. Defaults to "none" (no line).

stat_color

Color of the mean/median line. Defaults to "#d62728".

hover

Logical. When TRUE (default), hovering a ridge or its label raises and highlights it and shows its number of observations and mean.

x_title

Optional. Title of the x-axis.

x_title_font_size

Font size of the x-axis title. Defaults to 13.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

x_font_size

Font size of the x-axis tick labels. Defaults to 11.

y_font_size

Font size of the group labels. Defaults to 11.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of axis lines, ticks, and labels. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG ridgeline plot.

Examples

# 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)"
)

Create a Nightingale rose chart.

Description

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.

Usage

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
)

Arguments

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 NULL.

colors

Optional. A vector of colors, one per group when group is supplied, otherwise one per category (recycled if needed). A single color paints every wedge alike. Defaults to NULL, which uses an AntV-style ten-color palette.

sort

How to order the wedges: "none" (data or factor order, the default), "desc" or "asc" by category total.

inner_radius

Size of an empty hole in the middle, as a fraction of the outer radius (between 0 and 0.9). Defaults to 0.

start_angle

Angle, in degrees clockwise from 12 o'clock, at which the first wedge starts. Defaults to 0.

pad_angle

Gap between adjacent wedges, in radians. Defaults to 0.

corner_radius

Corner rounding of the wedges, in pixels. Defaults to 0.

opacity

Fill opacity of the wedges (0 to 1). Defaults to 0.9.

stroke_col

Color of the wedge outlines. Defaults to "white".

stroke_width

Width of the wedge outlines in pixels. Defaults to 1.

grid_lines

Approximate number of radial grid circles (value rings). Use 0 to hide them. Defaults to 4.

grid_col

Color of the grid circles and spokes. Defaults to "#e0e0e0".

grid_font_size

Font size of the grid value labels. Defaults to 10.

show_labels

Whether to display the category labels around the chart. Defaults to TRUE.

label_font_size

Font size of the category labels. Defaults to 11.

value_format

A d3-format specifier used to display values in the tooltip (e.g. ",.0f", ".1f", "$,.2s"). Defaults to ",.0f".

hover

Whether hovering a wedge pops it outward and shows a tooltip. Defaults to TRUE.

animate

Whether wedges grow out from the center on first render. Defaults to TRUE.

legend

Whether to display a legend of the groups (only used when group is supplied). Defaults to TRUE.

legend_font_size

Font size of the legend text. Defaults to 11.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of the title, labels and grid value labels. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG Nightingale rose chart.

Examples

# 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"
)

Create a Sankey diagram

Description

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.

Usage

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
)

Arguments

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 NULL, each row counts as 1. Rows with the same source and target are added up.

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: "source" (the default), "target", "gradient" (from the source colour to the target colour) or "grey".

align

How to place the nodes in columns: "justify" (the default; the end nodes go to the right edge), "left", "right" or "center".

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.

Value

An r2d3 htmlwidget.

Interactions

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.

Examples

# 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"))

Create an interactive scatter plot.

Description

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.

Usage

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"
)

Arguments

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 group. With a categorical group, a vector of colours (recycled; a named vector maps colours to groups). With a numeric group, two colours or more define the gradient. Defaults to a built-in palette (viridis for a numeric group).

size

The radius of the points in pixels when size_by is not used. Defaults to 4.

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; use "" to hide it.

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; use "" to hide it.

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 as.factor() to treat a numeric column as categories.

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 size_by. Defaults to c(3, 16).

label

Optional. The name of a column identifying each point. It is used as the tooltip title and by show_labels.

show_labels

Optional. Draws text labels next to points: TRUE labels every point, a character vector labels the points whose label matches. Requires label.

tooltip

TRUE (default) shows a tooltip on hover, FALSE disables it. A character vector of column names adds those columns to the tooltip.

trend

Adds a trend line: "none" (default), "lm" (linear regression) or "loess". With a categorical group, one line is fitted per group. With a log scale, the fit is computed on the log values.

ci

Logical. Draw the 95% confidence band around the trend line. Defaults to TRUE.

span

The LOESS smoothing parameter. Defaults to 0.75.

x_scale

The x-axis scale: "linear" (default) or "log". Rows with non-positive values are dropped with a log scale.

y_scale

The y-axis scale: "linear" (default) or "log".

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 NULL (default), it is shown when group or size_by is used.

brush

Logical. Enable drag-to-select and zoom. Defaults to TRUE.

animate

Logical. Animate the points when the chart is first drawn. Defaults to TRUE.

x_format, y_format

Optional. d3-format strings for the axes and the tooltip, e.g. ",.0f", ".1%" or "$,.2f".

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 NA to hide them.

Value

An interactive SVG scatter plot (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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)
)

Create a slope chart.

Description

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.

Usage

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
)

Arguments

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 start.

end_label

Header displayed above the right axis. Defaults to the value of end.

color_by_direction

Whether to color lines by direction of change (up_col, down_col, flat_col). If FALSE, every line uses line_col. Defaults to TRUE.

up_col

Color of lines that increase. Defaults to "#1a9850".

down_col

Color of lines that decrease. Defaults to "#d73027".

flat_col

Color of lines with no change. Defaults to "#888888".

line_col

Color of all lines when color_by_direction = FALSE. Defaults to "steelblue".

highlight

Optional. A character vector of categories (values of the group column) to emphasise. All other lines are drawn in muted_col. Defaults to NULL (no emphasis).

muted_col

Color of non-highlighted lines when highlight is used (their labels are drawn semi-transparent). Defaults to "#cccccc".

line_width

Width of the lines in pixels. Defaults to 2.

circle_radius

Radius of the end-point dots in pixels. Defaults to 4. Use 0 to hide the dots.

show_values

Whether to print the value next to each category label. Defaults to TRUE.

digits

Optional. Number of decimal places used to print the values. Defaults to NULL, which prints the values as they are.

label_font_size

Font size of the category and value labels. Defaults to 11.

header_font_size

Font size of the two axis headers. Defaults to 13.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of the two vertical axes, the headers, the title and the labels. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG slope chart.

Examples

# 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"
)

Create an interactive stacked area chart

Description

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.

Usage

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"
)

Arguments

data

A data frame, or a ts / mts object.

x

The time variable: a Date, a POSIXct date-time, a "yyyy-mm-dd" character column or a number. Not needed when data is an mts object.

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 colors is not given. Defaults to the ddplot palette.

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. When NULL, every numeric column other than x is stacked.

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 = TRUE.

controls

Logical. Show the Stacked / 100% buttons. Defaults to TRUE.

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 transform = "none".

legend

Logical. Show the interactive legend (click to hide or show a series, double-click to isolate it). When NULL (default), the legend is shown when there are two series or more.

end_labels

Logical. Label each line at its last visible point. When NULL (default), labels are shown when there are two series or more.

tooltip

Logical. Show the crosshair and the tooltip on hover. Defaults to TRUE.

navigator

Logical. Show the navigator (a miniature of the full series with a brush to select the visible range) under the chart. Defaults to TRUE; it is hidden automatically on very short charts.

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 TRUE.

zoom

Logical. Drag horizontally on the chart to zoom into a range; double-click to reset. Defaults to TRUE.

animate

Logical. Draw the lines in with an animation on first render. Defaults to TRUE.

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 transform = "percent".

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 NULL (default), it is picked from the frequency of the data (yearly, quarterly, monthly, daily or intraday).

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".

Details

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.

Value

An interactive SVG stacked area chart.

Examples

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"
)

Create a streamgraph.

Description

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.

Usage

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
)

Arguments

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), Date or POSIXct.

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 order = "none" and in the legend.

value

The name of the numeric, non-negative column holding the thickness of each layer. Rows sharing the same x and group are summed. NA values are treated as zero.

offset

The baseline of the stream. "wiggle" (default) minimises the weighted change in slope of the layers (the classic streamgraph), "silhouette" centres the stream symmetrically around zero, and "expand" normalises every x to 100% (a percent axis is then shown on the left).

order

The order in which layers are stacked. "insideOut" (default) puts the layers that peak earliest in the middle and the later ones on the outside, which works best with "wiggle". "none" keeps the order of the group column (factor levels or first appearance), "reverse" reverses it, and "ascending" / "descending" sort the layers by their total.

curve

The curve used to interpolate the layers: "basis" (default, smooth B-spline that never lets layers cross), "catmullRom", "monotoneX", "linear" or "step".

colors

Optional. A vector of colors, one per layer (recycled if shorter). Defaults to NULL, which uses color_palette.

color_palette

D3 categorical color scheme used when colors is NULL (e.g. "Tableau10", "Category10", "Set2", "Paired"). Defaults to "Tableau10".

opacity

Fill opacity of the layers (0 to 1). Defaults to 0.9.

stroke_col

Color of the thin line separating the layers. Defaults to "white".

stroke_width

Width of the separating line in pixels. Defaults to 0.5.

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 TRUE.

label_font_size

Font size of the inline layer labels. Defaults to 11.

label_col

Optional. Color of the inline labels. Defaults to NULL, which picks white or near-black automatically for contrast with each layer's fill.

tooltip

Whether to show the vertical crosshair and the tooltip listing every layer's value at the hovered x. Defaults to TRUE.

hover

Whether hovering a layer (or a legend item) highlights it and dims the others. Defaults to TRUE.

animate

Whether the stream is revealed from left to right on first render. Defaults to TRUE.

legend

Whether to show an interactive legend under the chart (hover to focus a layer, click to hide or show it). Defaults to TRUE.

legend_font_size

Font size of the legend text. Defaults to 11.

value_format

A d3-format specifier used to display the values in the tooltip (e.g. ",.0f", "$,.2s", ".1f"). Defaults to ",.2~f".

x_format

Optional. Format of the x values on the axis and in the tooltip header: a d3-format specifier for numeric x (e.g. "d") or a d3-time-format specifier for dates (e.g. "%b %Y"). Defaults to NULL, which picks a sensible format automatically.

x_ticks

Optional. Approximate number of x-axis ticks. Defaults to NULL (chosen from the chart width).

x_font_size

Font size of the x-axis tick labels. Defaults to 11.

grid_col

Color of the vertical grid lines drawn at each x tick. Use NA or "transparent" to hide them. Defaults to "#e6e6e6".

x_title

Optional. Title of the x-axis.

x_title_font_size

Font size of the x-axis title. Defaults to 13.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of the x-axis, the titles, the crosshair and the legend text. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG streamgraph.

Examples

# 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"
)

Create a zoomable sunburst chart.

Description

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.

Usage

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
)

Arguments

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. c("continent", "country"). A missing value (NA or "") at some level ends that row's path early, which makes ragged hierarchies possible. Rows that share the same path are summed.

value

Optional. The name of a numeric (non-negative) column that determines the size of each sector. Defaults to NULL, in which case each row counts as 1 (sector sizes are row counts).

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 NULL, which uses a built-in 10-color palette.

value_format

A d3-format specifier used to display values in the centre and the tooltip (e.g. ",.0f", "$,.2s", ".3~s"). Defaults to ",.0f".

inner_radius

Radius of the centre circle as a fraction of the chart's radius, between 0 and 0.9. The centre shows the current root and its value, and is clicked to zoom out. Defaults to 0.22.

corner_radius

Corner radius of the sectors in pixels. Defaults to 0.

pad_angle

Angular padding between sectors in radians (e.g. 0.005). Defaults to 0.

stroke_col

Color of the sector borders. Defaults to "white".

stroke_width

Width of the sector borders in pixels. Defaults to 1.

show_labels

Whether to display the sector labels. Labels are truncated or hidden automatically when a sector is too small. Defaults to TRUE.

label_rotate

Orientation of the sector labels: "radial" (default, along the radius) or "tangential" (along the arc).

label_font_size

Font size of the sector labels. Defaults to 11.

label_col

Optional. Color of the sector labels. Defaults to NULL, which picks white or near-black automatically for contrast with each sector's fill.

root_label

Label shown in the centre (and used as the root name) when the chart is not zoomed. Defaults to "Total".

center_font_size

Maximum font size of the centre label. Defaults to 13.

zoom

Whether clicking a sector zooms into it and clicking the centre zooms out. Defaults to TRUE.

hover

Whether to highlight the hovered sector (and its ancestors) and show a tooltip. Defaults to TRUE.

animate

Whether the sectors sweep in with an entrance animation. Defaults to TRUE.

duration

Duration of the zoom transition in milliseconds. Defaults to 750.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

text_col

Color of the title and the centre label. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG sunburst chart.

Examples

# 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"
)

Create a treemap chart.

Description

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.

Usage

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
)

Arguments

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 NULL.

tile

The tiling algorithm. One of "squarify" (default), "binary", "slice", "dice" or "sliceDice".

padding

Padding in pixels between rectangles (and around groups). Defaults to 2.

colors

Optional. A vector of colors. When group is supplied, one color is used per group; otherwise one color per rectangle. Colors are recycled if there are fewer colors than groups/rectangles. Defaults to NULL, which uses D3's Tableau 10 palette.

value_format

A d3-format specifier used to display values in the labels and tooltip (e.g. ",.0f", "$,.2s", ".3~s"). Defaults to ",.0f".

show_values

Whether to display the formatted value under each label. Defaults to TRUE.

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 11.

label_col

Optional. Color of the rectangle labels. Defaults to NULL, which picks white or near-black automatically for contrast with each rectangle's fill.

group_font_size

Font size of the group headers (only used when group is supplied). Defaults to 12.

stroke_col

Color of the rectangle borders. Defaults to "white".

stroke_width

Width of the rectangle borders in pixels. Defaults to 1.

hover

Whether to highlight the hovered rectangle and show a tooltip. Defaults to TRUE.

legend

Whether to display a legend of the groups (only used when group is supplied). Defaults to TRUE.

legend_font_size

Font size of the legend text. Defaults to 11.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

text_col

Color of the title and legend text. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG treemap chart.

Examples

# 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"
)

Create an animated, interactive treemap race.

Description

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.

Usage

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
)

Arguments

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), Date, POSIXct, or a factor or character column (factor levels, or the sorted values, give the order).

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: "resquarify" (default, squarified tiles that keep their place while the values change), "squarify" (the best squarified layout of every period, morphed from one period to the next), "binary" (the same with a balanced binary split), "slice" (vertical strips), "dice" (horizontal strips) or "sliceDice" (strips alternating with the depth). The strips keep the order of the items by average value.

fill

Optional. The colours of the tiles. With group, one colour per group (recycled, or a named vector mapping colours to groups); the items are drawn in shades of their group colour. Without group, one colour per item (recycled, or a named vector mapping colours to items). Defaults to the ddplot palette, the largest groups or items getting the first colours.

color_category

Optional. The name of a D3 categorical colour scheme (e.g. "Tableau10", "Set2"), see <https://github.com/d3/d3-scale-chromatic#categorical>, used when fill is not given.

color_by

How the tiles are coloured at first: "group" (default, the palette: by group, or by item without group) or "growth" (a heat map of the growth since the previous period, red for shrinking items, green for growing ones). It can be changed from the chart when controls = TRUE.

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 TRUE.

label_mode

What the labels show under the names at first: "value" (default), "share" (share of the total, or of the group when zoomed in) or "growth" (change since the previous period). It can be changed from the chart when controls = TRUE.

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 NULL (default), it is shown when group is used.

agg

How rows with the same item and period are combined: "sum" (default), "mean", "max", "min" or "last".

fill_gaps

Logical. Interpolate the value of an item between the periods where it is known. Defaults to TRUE; when FALSE, the tile shrinks away during the missing periods.

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 "Linear" (a steady animation) or "CubicInOut" (default, slows down on every period). See <https://github.com/d3/d3-ease>.

autoplay

Logical. Start playing when the chart scrolls into view. Defaults to TRUE.

loop

Logical. Start again from the first period at the end. Defaults to FALSE (it can be changed from the player).

controls

Logical. Show the player at the bottom and the label and colour buttons at the top. Defaults to TRUE.

start_frame

The period shown first: "first" (default), "last" or a period number (1 for the first one).

time_format

Optional. A d3-time-format string used for dates, e.g. "%b %Y". Chosen from the spacing of the periods when NULL.

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. ",.0f", ".1f" or ".3~s". Compact values ("1.23M") are used when NULL.

value_prefix, value_suffix

Optional. Text added before or after every value, e.g. "$" or " t".

tooltip

Logical. Show a tooltip on hover. Defaults to TRUE.

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Details

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.

Value

An animated SVG treemap (an r2d3 htmlwidget).

Interactions

  • 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.

Shiny

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.

Examples

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"
  )

Create a violin plot.

Description

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.

Usage

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
)

Arguments

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 sort is set). Defaults to NULL (a single violin).

bandwidth

Optional. The kernel bandwidth, expressed as the standard deviation of the Gaussian kernel (as in stats::density()), applied to every violin. When NULL (default), each violin uses its own bandwidth computed with Silverman's rule of thumb.

span

How far the density extends. "soft" (default) extends each violin two bandwidths beyond its minimum and maximum so the tails fade out smoothly; "hard" cuts the violin at the observed minimum and maximum.

scale

How the violin widths are scaled. "width" (default) gives every violin the same maximum width; "count" makes the width proportional to the number of observations, so larger groups look larger.

box

Logical. When TRUE (default), an inner box plot is drawn inside each violin: a box from the first to the third quartile, a white median line, and whiskers reaching the most extreme values within 1.5 IQR.

mean_line

Logical. When TRUE, a dashed line is drawn across each violin at the mean. Defaults to FALSE.

points

Which raw observations to draw on top of the violins: "outliers" (default, values beyond the whiskers), "all", or "none".

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 0.6. Use 0 to align them on the center line.

point_radius

Radius of the points in pixels. Defaults to 2.5.

point_opacity

Fill opacity of the points (0 to 1). Defaults to 0.7.

sort

How to order the violins from left to right. One of "none" (default, factor level order or order of appearance), "mean", or "median" (ascending).

color_palette

The violin colors. Either the name of a D3 categorical color scheme (e.g. "Category10", the default, which is also Plotly's classic colorway, "Tableau10", "Set2"), a single color applied to every violin, an unnamed vector of colors recycled over the groups (in their original order), or a named vector whose names match the group values.

fill_opacity

Fill opacity of the violins (0 to 1). Defaults to 0.5.

line_width

Width of the violin outline in pixels. Defaults to 1.5.

violin_width

Maximum width of a violin, as a fraction (0 to 1] of the space allotted to each group. Defaults to 0.8.

hover

Logical. When TRUE (default), hovering a violin highlights it and shows a tooltip with its summary statistics.

animate

Logical. When TRUE (default), the violins grow from their center line and the points fade in on first render.

y_title

Optional. Title of the y-axis.

y_title_font_size

Font size of the y-axis title. Defaults to 13.

x_title

Optional. Title of the x-axis.

x_title_font_size

Font size of the x-axis title. Defaults to 13.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

x_font_size

Font size of the group labels. Defaults to 11. Labels are rotated automatically when they do not fit.

y_font_size

Font size of the y-axis tick labels. Defaults to 11.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of axis lines, ticks, and labels. Defaults to "black".

grid_col

Color of the horizontal grid lines. Defaults to "#e6e6e6". Use "none" to hide them.

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG violin plot.

Examples

# 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)"
)

Create a waffle chart.

Description

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.

Usage

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
)

Arguments

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 10.

cols

Number of columns in the grid. Defaults to 10. The total number of cells is rows * cols.

total

Optional. The value represented by the whole grid. Defaults to the sum of value. When larger than that sum, the remaining cells are left unfilled and drawn with empty_col.

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 "#e5e5e5".

cell_padding

Gap between cells in pixels. Defaults to 2.

cell_radius

Corner radius of each cell in pixels. Defaults to 2. Use 0 for sharp squares.

direction

Fill direction. "row" (default) fills row by row starting from the bottom-left corner (the Pew Research style), "col" fills column by column starting from the bottom-left corner.

legend

Whether to display a legend showing each category and its percentage. Defaults to TRUE.

legend_font_size

Font size of the legend text. Defaults to 12.

hover

Whether hovering a cell or a legend entry highlights that category and shows a label with its value and percentage. Defaults to TRUE.

animate

Whether the cells pop in sequentially when the chart loads. Defaults to TRUE.

animation_duration

Total duration of the load animation in milliseconds. Defaults to 1200.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

text_col

Color of the title and legend text. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An SVG waffle chart.

Examples

# 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"
)

Create an interactive waterfall chart.

Description

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.

Usage

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
)

Arguments

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 "relative" (default — a delta added to the running total) or "total" (a bar spanning from zero to the current running total, used for subtotals and the final total).

positive_color

Fill color for bars representing an increase. Defaults to "#4CAF50".

negative_color

Fill color for bars representing a decrease. Defaults to "#F44336".

total_color

Fill color for "total" measure bars. Defaults to "#5C85D6".

connector

Logical. Whether to draw dashed connector lines between consecutive bars. Defaults to TRUE.

connector_color

Color of the connector lines. Defaults to "#aaaaaa".

show_labels

Logical. Whether to display the delta value above or below each bar. Defaults to TRUE.

label_font_size

Font size of the bar value labels. Defaults to 10.

title

Optional. Title of the chart.

title_font_size

Font size of the chart title. Defaults to 16.

x_title

Optional. Title of the x-axis.

x_title_font_size

Font size of the x-axis title. Defaults to 13.

y_title

Optional. Title of the y-axis.

y_title_font_size

Font size of the y-axis title. Defaults to 13.

x_font_size

Font size of the x-axis tick labels. Defaults to 11.

y_font_size

Font size of the y-axis tick labels. Defaults to 11.

opacity

Opacity of the bars (0 to 1). Defaults to 1.

font

The font family used for all text. Defaults to "Verdana, Geneva, Tahoma, sans-serif".

bg_col

Background color of the SVG. Defaults to "white".

axis_col

Color of axis lines, ticks, and labels. Defaults to "black".

width

Optional. The width of the SVG output.

height

Optional. The height of the SVG output.

Value

An interactive SVG waterfall chart.

Examples

# 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"
)