Skip to contents

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.

Value

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

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

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