Starting with ApexCharts

Victor Perrier

2024-09-05

The objective of this vignette is to show how to quickly build data visualizations with the ApexCharts JavaScript library, as well as to give an overview of the different graphics available.

Data used are from ggplot2 package.

library(ggplot2)
library(scales)
library(apexcharter)

Bar charts

Simple bar charts can be created with:

data("mpg")

apex(data = mpg, type = "column", mapping = aes(x = manufacturer))
404030302020101000audiaudichevroletchevroletdodgedodgefordfordhondahondahyundaihyundaijeepjeepland roverland roverlincolnlincolnmercurymercurynissannissanpontiacpontiacsubarusubarutoyotatoyotavolkswagenvolkswagen
Download SVG
Download PNG
Download CSV

Flipping coordinates can be done by using type = "bar":

apex(data = mpg, type = "bar", mapping = aes(x = manufacturer))
audiaudichevroletchevroletdodgedodgefordfordhondahondahyundaihyundaijeepjeepland roverland roverlincolnlincolnmercurymercurynissannissanpontiacpontiacsubarusubarutoyotatoyotavolkswagenvolkswagen404030302020101000
Download SVG
Download PNG
Download CSV

To create a dodge bar charts, use aesthetic fill :

apex(data = mpg, type = "column", mapping = aes(x = manufacturer, fill = year))
1999
2008
25252020151510105500audiaudichevroletchevroletdodgedodgefordfordhondahondahyundaihyundaijeepjeepland roverland roverlincolnlincolnmercurymercurynissannissanpontiacpontiacsubarusubarutoyotatoyotavolkswagenvolkswagen
Download SVG
Download PNG
Download CSV

For stacked bar charts, specify option stacked in ax_chart :

apex(data = mpg, type = "column", mapping = aes(x = manufacturer, fill = year)) %>% 
  ax_chart(stacked = TRUE)
1999
2008
404030302020101000audiaudichevroletchevroletdodgedodgefordfordhondahondahyundaihyundaijeepjeepland roverland roverlincolnlincolnmercurymercurynissannissanpontiacpontiacsubarusubarutoyotatoyotavolkswagenvolkswagen
Download SVG
Download PNG
Download CSV

Line charts

Simple line charts can be created with (works with character, Date or POSIXct):

data("economics")

apex(data = economics, type = "line", mapping = aes(x = date, y = uempmed))
30.0030.0025.0025.0020.0020.0015.0015.0010.0010.005.005.000.000.0019681968197119711974197419771977198019801983198319861986198919891992199219951995199819982001200120042004200720072010201020132013
Download SVG
Download PNG
Download CSV

To represent several lines, use a data.frame in long format and the group aesthetic:

data("economics_long")

apex(data = economics_long, type = "line", mapping = aes(x = date, y = value01, group = variable)) %>% 
  ax_yaxis(decimalsInFloat = 2) # number of decimals to keep
pce
pop
psavert
uempmed
unemploy
1.001.000.800.800.600.600.400.400.200.200.000.0019681968197119711974197419771977198019801983198319861986198919891992199219951995199819982001200120042004200720072010201020132013
Download SVG
Download PNG
Download CSV

Area charts

Create area charts with type = "area":

data("eco2mix", package = "apexcharter")

apex(eco2mix, aes(datetime, production, fill = source), type = "area") %>% 
  ax_chart(animations = list(enabled = FALSE), stacked = TRUE) %>% 
  ax_stroke(width = 1) %>% 
  ax_fill(opacity = 1, type = "solid") %>% 
  ax_tooltip(x = list(format = "dd MMM, HH:mm")) %>% 
  ax_yaxis(labels = list(formatter = format_num("~", suffix = "MW"))) %>% 
  ax_colors_manual(
    list(
      "bioenergies" = "#156956",
      "fuel" = "#80549f",
      "coal" = "#a68832",
      "solar" = "#d66b0d",
      "gas" = "#f20809",
      "wind" = "#72cbb7",
      "hydraulic" = "#2672b0",
      "nuclear" = "#e4a701",
      "pumping" = "#0e4269"
    )
  ) %>% 
  ax_labs(
    title = "Electricity generation by sector in France",
    subtitle = "Data from \u00e9CO\u2082mix"
  )
pumping
wind
solar
nuclear
hydraulic
gas
coal
fuel
bioenergies
Electricity generation by sector in FranceData from éCO₂mix60000MW60000MW50000MW50000MW40000MW40000MW30000MW30000MW20000MW20000MW10000MW10000MW0MW0MW−10000MW−10000MW08 Jun08 Jun09 Jun09 Jun10 Jun10 Jun11 Jun11 Jun12 Jun12 Jun13 Jun13 Jun14 Jun14 Jun
Download SVG
Download PNG
Download CSV

You can create ribbon charts using ymin and ymax aesthetics :

data("temperatures", package = "apexcharter")

apex(
  temperatures, 
  aes(x = date, ymin = low, ymax = high), 
  type = "rangeArea", 
  serie_name = "Low/High (2018-2021)"
) %>% 
  add_line(aes(date, `2023`)) %>% 
  ax_chart(animations = list(enabled = FALSE)) %>% 
  ax_yaxis(tickAmount = 7, labels = list(formatter = format_num("~", suffix = "°C"))) %>% 
  ax_colors(c("#8485854D", "#FF0000")) %>%
  ax_stroke(width = c(1, 2)) %>% 
  ax_fill(opacity = 1, type = "solid") %>% 
  ax_labs(
    title = "Temperatures in 2023 with range from 2018 to 2021",
    subtitle = "Data from ENEDIS"
  )
Low/High (2018-2021)
2023
Temperatures in 2023 with range from 2018 to 2021Data from ENEDIS35°C35°C30°C30°C25°C25°C20°C20°C15°C15°C10°C10°C5°C5°C0°C0°CJan '22Jan '22Feb '22Feb '22Apr '22Apr '22May '22May '22Jun '22Jun '22Jul '22Jul '22Aug '22Aug '22Sep '22Sep '22Oct '22Oct '22Nov '22Nov '22
Download SVG
Download PNG
Download CSV

Scatter charts

Simple bar charts can be created with:

apex(data = mtcars, type = "scatter", mapping = aes(x = wt, y = mpg))
3535303025252020151510101.01.02.02.03.03.04.04.05.05.06.06.0
Download SVG
Download PNG
Download CSV

Color points according to a third variable:

apex(data = mtcars, type = "scatter", mapping = aes(x = wt, y = mpg, fill = cyl))
6
4
8
3535303025252020151510101.01.02.02.03.03.04.04.05.05.06.06.0
Download SVG
Download PNG
Download CSV

And change point size using z aesthetics:

apex(data = mtcars, type = "scatter", mapping = aes(x = wt, y = mpg, z = scales::rescale(qsec)))
3535303025252020151510101.01.02.02.03.03.04.04.05.05.06.06.0
Download SVG
Download PNG
Download CSV

Pie & donut charts

Simple pie charts can be created with:

poll <- data.frame(
  answer = c("Yes", "No"),
  n = c(254, 238)
)

apex(data = poll, type = "pie", mapping = aes(x = answer, y = n))
Yes
No
51.6%48.4%

It’s also possible to make donut chart:

apex(data = poll, type = "donut", mapping = aes(x = answer, y = n))
Yes
No
51.6%48.4%

Radial charts

Simple radial charts can be created with (here we pass values directly in aes, but you can use a data.frame) :

apex(data = NULL, type = "radialBar", mapping = aes(x = "My value", y = 65))
My value65%

Multi radial chart (more than one value):

fruits <- data.frame(
  name = c('Apples', 'Oranges', 'Bananas', 'Berries'),
  value = c(44, 55, 67, 83)
)

apex(data = fruits, type = "radialBar", mapping = aes(x = name, y = value))

Radar charts

Simple radar charts can be created with:

mtcars$model <- rownames(mtcars)

apex(data = head(mtcars), type = "radar", mapping = aes(x = model, y = qsec))
Mazda RX4Mazda RX4 WagDatsun 710Hornet 4 DriveHornet SportaboutValiant2520151050
Download SVG
Download PNG
Download CSV

With a grouping variable:

# extremely complicated reshaping
new_mtcars <- reshape(
  data = head(mtcars), 
  idvar = "model", 
  varying = list(c("drat", "wt")),
  times = c("drat", "wt"),
  direction = "long",
  v.names = "value",
  drop = c("mpg", "cyl", "hp", "dist", "qsec", "vs", "am", "gear", "carb")
)

apex(data = new_mtcars, type = "radar", mapping = aes(x = model, y = value, group = time))
drat
wt
Mazda RX4Mazda RX4 WagDatsun 710Hornet 4 DriveHornet SportaboutValiant43210
Download SVG
Download PNG
Download CSV

Polar area

With some custom options for color mapping:

apex(mtcars, aes(rownames(mtcars), mpg), type = "polarArea") %>% 
  ax_legend(show = FALSE) %>% 
  ax_colors(col_numeric("Blues", domain = NULL)(mtcars$mpg)) %>% 
  ax_fill(opacity = 1) %>% 
  ax_stroke(width = 0) %>% 
  ax_tooltip(fillSeriesColor = FALSE)
40302010

Heatmap

Create a heatmap with :

# create some data
sales <- expand.grid(year = 2010:2020, month = month.name)
sales$value <- sample(-10:30, nrow(sales), TRUE)

apex(
  data = sales,
  type = "heatmap", 
  mapping = aes(x = year, y = month, fill = value)
) %>% 
  ax_dataLabels(enabled = FALSE) %>% 
  ax_colors("#008FFB")
DecemberDecemberNovemberNovemberOctoberOctoberSeptemberSeptemberAugustAugustJulyJulyJuneJuneMayMayAprilAprilMarchMarchFebruaryFebruaryJanuaryJanuary2010201020112011201220122013201320142014201520152016201620172017201820182019201920202020
Download SVG
Download PNG
Download CSV

Treemap

Create a treemap with:

data("mpg", package = "ggplot2")

apex(mpg, aes(x = manufacturer), "treemap")
audichevroletdodgefordhondahyundaijeepland roverlincolnmercurynissanpontiacsubarutoyotavolkswagen
Download SVG
Download PNG
Download CSV

Candlestick

Create a candlestick chart with:

data("candles", package = "apexcharter")

apex(
  candles, 
  aes(x = datetime, open = open, close = close, low = low, high = high),
  type = "candlestick"
)
6660.006660.006640.006640.006620.006620.006600.006600.006580.006580.006560.006560.0023:0023:0002:0002:0005:0005:0008:0008:0011:0011:0014:0014:0017:0017:0020:0020:0023:0023:0002:0002:00
Download SVG
Download PNG
Download CSV

Boxplot

Create boxplot (without outliers for now) with:

data("mpg", package = "ggplot2")
apex(mpg, aes(hwy, class), "boxplot") %>% 
  ax_plotOptions(
    boxPlot = boxplot_opts(color.upper = "#8BB0A6", color.lower = "#8BB0A6" )
  ) %>% 
  ax_stroke(colors = list("#2A5769")) %>% 
  ax_grid(
    xaxis = list(lines = list(show = TRUE)),
    yaxis = list(lines = list(show = FALSE))
  )
2seater2seatercompactcompactmidsizemidsizeminivanminivanpickuppickupsubcompactsubcompactsuvsuv4040353530302525202015151010
Download SVG
Download PNG
Download CSV

Dumbbell charts

Create Dumbbell chart with:

data("life_expec", package = "apexcharter")

apex(life_expec, aes(country, x = `1972`, xend = `2007`), type = "dumbbell") %>% 
  ax_plotOptions(
    bar = bar_opts(
      dumbbellColors = list(list("#3d85c6", "#fb6003"))
    )
  ) %>% 
  ax_colors("#BABABA") %>% 
  ax_labs(
    title = "Life expectancy : 1972 vs. 2007",
    subtitle = "Data from Gapminder dataset",
    x = "Life expectancy at birth, in years"
  )
BotswanaBotswanaGhanaGhanaIranIranLiberiaLiberiaMalaysiaMalaysiaMexicoMexicoNigeriaNigeriaPakistanPakistanPhilippinesPhilippinesZambiaZambia80807070606050504040Life expectancy at birth, in yearsLife expectancy : 1972 vs. 2007Data from Gapminder dataset
Download SVG
Download PNG
Download CSV

Slope charts

Create a slope chart with:

data("life_expec_long", package = "apexcharter")

apex(
  life_expec_long,
  mapping = aes(x = year, y = lifeExp, fill = country),
  type = "slope",
  height = "700px"
) %>% 
  ax_chart(animations = list(enabled = FALSE)) %>% 
  # aurora nord12 = #d08770 / aurora nord14 = #a3be8c -> darken colorspace::darken(, amount = 0.3)
  ax_colors(ifelse(unique(life_expec_long[, c("country", "type")])$type == "decreased", "#955945", "#6A8354")) %>% 
  ax_labs(
    title = "Life expectancy : 1972 vs. 2007",
    subtitle = "Data from Gapminder dataset",
    x = "Life expectancy at birth, in years"
  ) %>% 
  # ax_dataLabels(enabled = FALSE) %>% # show or note the labels + values
  ax_xaxis(position = "bottom")
Life expectancy : 1972 vs. 2007Data from Gapminder datasetBotswana: 56Botswana: 50.7Ghana: 49.9Ghana: 60Iran: 55.2Iran: 71Liberia: 42.6Liberia: 45.7Malaysia: 63Malaysia: 74.2Mexico: 62.4Mexico: 76.2Nigeria: 42.8Nigeria: 46.9Pakistan: 51.9Pakistan: 65.5Philippines: 58.1Philippines: 71.7Zambia: 50.1Zambia: 42.41972197220072007Life expectancy at birth, in years