This vignette focuses on line and area charts, and more generally on time series: how to customize series, axes and legend, how to navigate in the data with zoom and a subchart (brush), how to synchronize several charts and how to display large datasets.
library(apexcharter)
data("economics", package = "ggplot2")
data("economics_long", package = "ggplot2")
data("eco2mix", package = "apexcharter")
data("temperatures", package = "apexcharter")Line and area charts
When the variable used on the x-axis is a Date or a
POSIXct, the x-axis is automatically a datetime axis:
Several types are available to draw lines and areas:
"line", "spline" (smoothed line),
"step", "area", "area-spline" and
"area-step":
To draw several series, use a group (or
colour/fill) aesthetic, data must be in long
format:
eco_long <- subset(economics_long, variable %in% c("psavert", "uempmed"))
apex(eco_long, aes(x = date, y = value, group = variable), type = "line")A range between two values can be drawn with
type = "rangeArea", use add_line() to add a
line over it:
apex(
data = temperatures,
mapping = aes(x = date, ymin = low, ymax = high),
type = "rangeArea",
serie_name = "Low/High (2018-2021)"
) %>%
add_line(aes(date, `2023`), serie_name = "2023") %>%
ax_colors(c("#8485854D", "#FF0000")) %>%
ax_stroke(width = c(1, 2)) %>%
ax_fill(opacity = 1, type = "solid") %>%
ax_yaxis(labels = list(formatter = format_num("~", suffix = "°C"))) %>%
ax_tooltip(x = list(format = "dd MMMM"))Series options
Colors
Use ax_colors() to set colors in the order of the
series, or ax_colors_manual() to match a color to the name
of a serie:
apex(eco_long, aes(x = date, y = value, group = variable), type = "line") %>%
ax_colors_manual(list(
psavert = "#112446",
uempmed = "#E91E63"
))Stroke and markers
ax_stroke() controls the lines: width, curve and dashes.
A vector can be used to set a different value for each serie:
apex(eco_long, aes(x = date, y = value, group = variable), type = "line") %>%
ax_stroke(
width = c(3, 1),
curve = c("smooth", "stepline"),
dashArray = c(0, 4)
)By default markers are not displayed on lines, but you can show them, or only display them when hovering the chart:
Fill for area charts
Area can be filled with a gradient using ax_fill():
apex(economics, aes(x = date, y = unemploy), type = "area") %>%
ax_fill(
type = "gradient",
gradient = list(
shadeIntensity = 1,
opacityFrom = 0.7,
opacityTo = 0.1,
stops = c(0, 90, 100)
)
) %>%
ax_stroke(width = 2)Areas can be stacked with ax_chart(stacked = TRUE):
Forecast
The last points of a serie can be displayed as a forecast with
ax_forecast_data_points():
apex(tail(economics, 36), aes(x = date, y = psavert), type = "line") %>%
ax_forecast_data_points(count = 6, dashArray = 4)X-axis
Labels format
On a datetime axis, labels are formatted automatically according to
the zoom level. You can force a format with labels$format,
or change the format used for each level with
labels$datetimeFormatter:
apex(economics, aes(x = date, y = psavert), type = "line") %>%
ax_xaxis(
labels = list(
datetimeFormatter = list(
year = "yyyy",
month = "MMM yyyy",
day = "dd MMM"
)
)
) %>%
ax_tooltip(x = list(format = "MMMM yyyy"))Dates are displayed in UTC by default. With POSIXct
data, use datetimeUTC = FALSE to display them in the time
zone of the viewer:
Range of the axis
Use min and max to restrict the visible
range (dates must be converted with format_date()), and
tickAmount to set the number of ticks:
apex(economics, aes(x = date, y = psavert), type = "line") %>%
ax_xaxis(
min = format_date("2000-01-01"),
max = format_date("2010-01-01"),
tickAmount = 10
)Annotations
Highlight a period or an event on the x-axis with
add_shade() and add_event(), or shade all
week-ends with add_shade_weekend():
apex(economics, aes(x = date, y = unemploy), type = "line") %>%
add_shade(from = "2007-12-01", to = "2009-06-01", label = "Great Recession") %>%
add_event(when = "2001-09-11", label = "9/11")
apex(eco2mix, aes(x = datetime, y = production, group = source), type = "line") %>%
add_shade_weekend()Y-axis
Labels and scale
Use format_num() to format labels (it uses d3-format specifiers), and
min, max, tickAmount to control
the scale:
apex(economics, aes(x = date, y = psavert / 100), type = "line") %>%
ax_yaxis(
min = 0,
max = 0.2,
tickAmount = 4,
labels = list(formatter = format_num(".0%"))
)Format can be localized and you can add a prefix or a suffix:
apex(economics, aes(x = date, y = unemploy * 1000), type = "line") %>%
ax_yaxis(
labels = list(formatter = format_num(",.0f", locale = "fr-FR", suffix = " pers."))
)A logarithmic scale can be used with
logarithmic = TRUE:
Titles and reference lines
Use ax_labs() to set the axis titles, and
add_hline() to add a horizontal line:
Secondary axis
When series have different scales, a secondary y-axis can be added
with ax_yaxis2():
Legend
The legend is displayed as soon as there are several series. Its position and its markers can be customized, as well as what happens when you click or hover an item:
apex(eco_long, aes(x = date, y = value, group = variable), type = "line") %>%
ax_legend(
position = "top",
horizontalAlign = "left",
fontSize = "14px",
markers = list(shape = "line", size = 8),
onItemClick = list(toggleDataSeries = TRUE),
onItemHover = list(highlightDataSeries = TRUE)
)Legend labels can be modified with a JavaScript function, for example to display the value of the series hovered:
apex(eco_long, aes(x = date, y = value, group = variable), type = "line") %>%
ax_legend(
position = "top",
tooltipHoverFormatter = JS(
"function(seriesName, opts) {",
" var value = opts.w.globals.series[opts.seriesIndex][opts.dataPointIndex];",
" return seriesName + ': <b>' + value + '</b>';",
"}"
)
)For a single serie, the legend is hidden by default, use
showForSingleSeries = TRUE to display it.
Zoom
On a datetime axis, zoom is enabled by default: select an area of the
chart to zoom in, the toolbar allows to reset the zoom, or to switch to
pan mode. Zoom can be configured with ax_chart(), for
example to automatically adapt the y-axis to the visible data and use
the mouse wheel:
apex(economics, aes(x = date, y = unemploy), type = "area") %>%
ax_chart(
zoom = list(
enabled = TRUE,
type = "x",
autoScaleYaxis = TRUE,
allowMouseWheelZoom = TRUE
),
toolbar = list(
autoSelected = "zoom",
tools = list(download = FALSE)
)
)Use type = "xy" to zoom on both axes, or
enabled = FALSE to disable zoom. In Shiny, you can retrieve
the zoomed range with set_input_zoom().
Subchart (brush)
A subchart can be used to navigate in a main chart: the area selected
in the subchart is displayed in the main chart. Give an id
to the main chart, and use it as target in the
brush option of the subchart. Option selection
defines the initial range:
apex(economics, aes(x = date, y = psavert), type = "line", height = "300px") %>%
ax_chart(
id = "economics-main",
toolbar = list(autoSelected = "pan", show = FALSE)
) %>%
ax_labs(title = "Personal savings rate")
apex(economics, aes(x = date, y = psavert), type = "area", height = "130px") %>%
ax_chart(
brush = list(
enabled = TRUE,
target = "economics-main",
autoScaleYaxis = TRUE
),
selection = list(
enabled = TRUE,
xaxis = list(
min = format_date("1990-01-01"),
max = format_date("2000-01-01")
)
)
) %>%
ax_yaxis(tickAmount = 2, labels = list(show = FALSE)) %>%
ax_fill(
type = "gradient",
gradient = list(opacityFrom = 0.9, opacityTo = 0.1)
)Synchronize charts
Several charts can be synchronized (tooltip and zoom) by giving them
the same id with argument synchronize. For a correct
alignment, y-axis labels must have the same width in all charts, set it
with minWidth:
apex(economics, aes(x = date, y = psavert), type = "line", synchronize = "economics", height = "200px") %>%
ax_yaxis(labels = list(minWidth = 40)) %>%
ax_labs(title = "Personal savings rate")
apex(economics, aes(x = date, y = uempmed), type = "line", synchronize = "economics", height = "200px") %>%
ax_yaxis(labels = list(minWidth = 40)) %>%
ax_labs(title = "Duration of unemployment")
apex(economics, aes(x = date, y = unemploy), type = "area", synchronize = "economics", height = "200px") %>%
ax_yaxis(labels = list(minWidth = 40, formatter = format_num("~s"))) %>%
ax_labs(title = "Number of unemployed (thousands)")See also the article Synchronize charts with each other and
the Shiny example with run_demo_sync().
Performance
Let’s create a time series with 20,000 points:
set.seed(42)
n <- 20000
big <- data.frame(
time = seq(as.POSIXct("2024-01-01", tz = "UTC"), by = "5 min", length.out = n),
value = cumsum(rnorm(n))
)With a lot of points, some options make the chart faster: disable animations, use a thin stroke and no markers. The tooltip is also less costly if it is not shared between series.
Canvas renderer
By default series are drawn as SVG, with one element for each serie.
With renderer = "canvas", series are drawn in a
<canvas> element, which is much faster with a large
number of points (the rest of the chart: axes, legend, annotations… is
still drawn with SVG):
apex(big, aes(x = time, y = value), type = "line") %>%
ax_chart(
renderer = "canvas",
animations = list(enabled = FALSE)
) %>%
ax_stroke(width = 1)With renderer = "auto", the canvas renderer is used only
above a number of points defined by rendererThreshold
(8,000 by default). Note that some features are not supported by the
canvas renderer: in that case the chart uses SVG (pattern or image
fill), and clicking a data point (dataPointSelection event,
used by set_input_click()) only works with SVG.
Downsampling with LTTB
Another way to handle large datasets is to reduce the number of
points actually drawn. With option dataReducer, ApexCharts
uses the LTTB
(Largest-Triangle-Three-Buckets) algorithm, which keeps the visual shape
of the serie with a small number of points. Downsampling is zoom-aware:
when you zoom in, the visible window is downsampled again from the full
data, so details appear progressively:
apex(big, aes(x = time, y = value), type = "line") %>%
ax_chart(
dataReducer = list(
enabled = TRUE,
targetPoints = 500, # number of points to draw
threshold = 1000 # downsample only series with more points than this
),
zoom = list(autoScaleYaxis = TRUE),
animations = list(enabled = FALSE)
) %>%
ax_stroke(width = 1)Downsampling applies to line and area charts; for range data
("rangeArea") and candlesticks, points are aggregated by
buckets so that extremes are kept.
Both options can be combined:
Data size
Even with downsampling, all the data are sent to the browser. For
very large datasets, consider aggregating data in R first. The
conversion of data to JSON can also be accelerated by using another
serializer than jsonlite, for example yyjsonr:
options("APEXCHART_TOJSON_FUNC" = function(x) {
yyjsonr::write_json_str(x, opts = yyjsonr::opts_write_json(auto_unbox = TRUE))
})