Skip to contents

This example demonstrates how to create a multi-series line chart using Mosaic, showing unemployment rates across different metro divisions with interactive features.

This example shows the usage of select to add interactivity to plots.

Multi-Series Line Chart

library(mosaic)

spec <- list(
  meta = list(
    title = "Line Multi-Series",
    description = "This line chart shows the unemployment rate of various U.S. metro divisions
from 2000 through 2013. On hover, the closest data point to the pointer and
its associated series is highlighted. Highlighting of series is performed
using `nearestX` and `highlight` interactors. Point and text annotations
instead use the mark `select` filter option.",
    credit = "Adapted from a [D3 example](https://observablehq.com/@d3/multi-line-chart/2).
Data from the [Bureau of Labor Statistics](https://www.bls.gov/)."
  ),
  data = list(
    bls_unemp = list(file = "data/bls-metro-unemployment.parquet")
  ),
  plot = list(
    list(mark = "ruleY", data = list(0)),
    list(
      mark = "lineY",
      data = list(from = "bls_unemp", optimize = FALSE),
      x = "date", y = "unemployment", z = "division",
      stroke = "steelblue", strokeOpacity = 0.9, curve = "monotone-x"
    ),
    list(select = "nearestX", channels = list("z"), as = "$curr"),
    list(select = "highlight", by = "$curr"),
    list(
      mark = "dot",
      data = list(from = "bls_unemp"),
      x = "date", y = "unemployment", z = "division",
      r = 2, fill = "currentColor", select = "nearestX"
    ),
    list(
      mark = "text",
      data = list(from = "bls_unemp"),
      x = "date", y = "unemployment", text = "division",
      fill = "currentColor", dy = -8, select = "nearestX"
    )
  ),
  marginLeft = 24,
  xLabel = NULL,
  xTicks = 10,
  yLabel = "Unemployment (%)",
  yGrid = TRUE,
  style = "overflow: visible;"
)

mosaic(spec)