Interactive Visualization in R with apexcharter

Interactive Visualization in R with apexcharter

This is my notes for learning Interactive Visualization in R with apexcharter and Create Interactive Chart with the JavaScript ‘ApexCharts’ Library • apexcharter.

Simple example

R
1
2
3
4
5
6
7
8
9
# install.packages("apexcharter")
library(apexcharter)
library(tidyverse)

# bar
mtcars %>%
count(cyl) %>%
apex(type = "bar",
mapping = aes(x = "cyl", y = n))

R
1
2
3
4
5
6
7
8
9
10
11
# Heatmap
mtcars %>%
select_if(is.numeric) %>%
cor() %>%
as_tibble() %>%
rownames_to_column("col") %>%
pivot_longer(cols = -col, names_to = "type") %>%
mutate(value = round(value, 2)) %>%
apex(type = "heatmap",
mapping = aes(x = col, y = type,
fill = value))

R
1
2
3
4
5
6
7
8
9
# Time Series (Line) Graph
df <- tibble(
Y = as.matrix(EuStockMarkets),
date = time(EuStockMarkets)
)
df %>%
apex(type = "line",
mapping = aes(x = date, y = Y[,"DAX"])) %>%
ax_yaxis(decimalsInFloat = 0)

Quick Charts

R
1
2
3
4
5
6
library(apexcharter)
mpg %>%
count(manufacturer) %>%
apex(type = "bar",
mapping = aes(x = manufacturer,
y = n))

R
1
2
3
4
5
6
# With datetime
economics %>%
apex(type = "line",
mapping = aes(x = date,
y = uempmed)) %>%
ax_stroke(width = 2)

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Full API
n_manufac <- mpg %>%
count(manufacturer)
apexchart() %>%
ax_chart(type = "bar") %>%
ax_plotOptions(
bar = bar_opts(
horizontal = FALSE,
endingShape = "flat",
columnWidth = "70%",
dataLabels = list(
position = 'top'
)
)
) %>%
ax_grid(
show = TRUE,
position = "front",
borderColor = "#FFF"
) %>%
ax_series(list(
name = "Count",
data = n_manufac$n
)) %>%
ax_colors("#112446") %>%
ax_xaxis(categories = n_manufac$manufacturer) %>%
ax_title(text = "Number of models") %>%
ax_subtitle(text = "Data Source: `ggplot2`")

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Raw API
apexchart(ax_opts = list(
chart = list(
type = "line"
),
stroke = list(
curve = "smooth"
),
grid = list(
borderColor = "#e7e7e7",
row = list(
colors = c("#f3f3f3", "transparent"),
opacity = 0.5
)
),
dataLabels = list(
enabled = TRUE
),
markers = list(style = "inverted", size = 6),
series = list(
list(
name = "High",
data = c(28, 29, 33, 36, 32, 32, 33)
),
list(
name = "Low",
data = c(12, 11, 14, 18, 17, 13, 13)
)
),
title = list(
text = "Average High & Low Temperature",
align = "left"
),
xaxis = list(
categories = month.abb[1:7]
),
yaxis = list(
title = list(text = "Temperature"),
labels = list(
formatter = htmlwidgets::JS("function(value){return value + '°C'}")
)
)
))

Starting with ApexCharts

R
1
2
3
4
mpg %>% 
count(manufacturer) %>%
apex(type = "column",
mapping = aes(x = manufacturer, y = n))

R
1
2
3
4
5
6
mpg %>% 
count(manufacturer, year) %>%
apex(type = "bar",
mapping = aes(x = manufacturer,
y = n,
fill = year))

R
1
2
3
4
5
6
7
mpg %>% 
count(manufacturer, year) %>%
apex(type = "bar",
mapping = aes(x = manufacturer,
y = n,
fill = year)) %>%
ax_chart(stacked = TRUE)

R
1
2
3
4
5
6
7
economics_long %>% 
group_by(variable) %>%
slice(n()-100:n()) %>%
apex(type = "line",
mapping = aes(x = date, y = value01,
group = variable)) %>%
ax_yaxis(decimalsInFloat = 2)

R
1
2
3
4
5
6
7
8
9
10
11
12
economics_long %>% 
group_by(variable) %>%
slice(n()-100:n()) %>%
apex(
type = "area",
mapping = aes(x = date,
y = value01,
fill = variable)
) %>%
ax_yaxis(decimalsInFloat = 2) %>%
ax_chart(stacked = TRUE) %>%
ax_yaxis(max = 2.5, tickAmount = 4)

R
1
2
3
4
5
6
mtcars %>% 
apex(type = "scatter",
mapping = aes(x = wt, y = mpg,
fill = cyl,
z = scales::rescale(qsec))) %>%
ax_xaxis(tickAmount = 5)

R
1
2
3
4
5
6
7
8
tibble(
answer = c("Yes", "No"),
n = c(254, 238)
) %>%
apex(
type = "pie",
mapping = aes(x = answer, y = n)
)

R
1
2
3
4
5
6
apex(
data = NULL,
type = "radialBar",
mapping = aes(x = "My Value",
y = 65)
)

R
1
2
3
4
5
6
tibble(
name = c("Apple", "Oranges", "Bananas", "Berries"),
value = c(44, 55, 67, 83)
) %>%
apex(type = "radialBar",
mapping = aes(x = name, y = value))

R
1
2
3
4
mtcars$model <- rownames(mtcars)
apex(data = head(mtcars),
type = "radar",
mapping = aes(x = model, y = qsec))

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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")
) %>%
as_tibble() %>%
apex(type = "radar",
mapping = aes(x = model,
y = value,
group = time))

R
1
2
3
4
5
6
7
8
txhousing %>% 
dplyr::filter(city %in% head(unique(city)), year %in% c(2000, 2001)) %>%
rename(val_med = median) %>%
apex(type = "heatmap",
aes(x = date, y = city,
fill = scales::rescale(val_med))) %>%
ax_dataLabels(enabled = F) %>%
ax_colors("#008FFB")

Labs: title, subtitle & axis

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
diamonds %>% 
count(cut) %>%
apex(type = "column",
aes(x = cut, y = n)) %>%
ax_title(
text = "Cut distribution",
align = "center",
style = list(fontSize = "22px")
) %>%
ax_subtitle(
text = "Data from ggplot2",
align = "center",
style = list(fontSize = "16px",
color = "#BDBDBD")
) %>%
ax_yaxis(
title = list(text = "Count",
style = list(
fontSize = "14px",
color = "#BDBDBD"
))
) %>%
ax_xaxis(
title = list(text = "Cut",
style = list(
fontSize = "14px",
color = "#BDBDBD"
))
)

Options & styles for lines

R
1
2
3
4
5
6
7
8
9
10
economics <- tail(economics, 50)
economics_long <- economics_long %>%
dplyr::filter(variable %in% c("pce", "pop")) %>%
group_by(variable) %>%
slice(tail(row_number(), 20))

economics %>%
apex(type = "line",
aes(x = date, y = uempmed)) %>%
ax_stroke(curve = "smooth")

R
1
2
3
4
economics %>% 
apex(type = "line",
aes(x = date, y = uempmed)) %>%
ax_stroke(curve = "stepline")

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
economics %>% 
apex(type = "line",
aes(x = date, y = uempmed)) %>%
ax_fill(
type = "gradient",
gradient = list(
shade = "dark",
gradientToColors = list("#FDD835"),
shadeIntensity = 1,
type = "horizontal",
opacityFrom = 1,
opacityTo = 1,
stops = c(0, 100, 100, 100)
)
)

R
1
2
3
4
economics %>% 
apex(type = "area",
aes(x = date, y = uempmed)) %>%
ax_fill(type = "solid", opacity = 1)

R
1
2
3
4
economics %>% 
apex(type = "line",
aes(x = date, y = uempmed)) %>%
ax_stroke(width = 1)

R
1
2
3
4
economics %>% 
apex(type = "line",
aes(x = date, y = uempmed)) %>%
ax_stroke(dashArray = 6)

R
1
2
3
4
5
economics %>% 
apex(type = "line",
aes(x = date, y = uempmed)) %>%
ax_markers(size = 6) %>%
ax_dataLabels(enabled = T)

R
1
2
3
4
5
6
7
8
9
economics_long %>% 
apex(type = "line",
aes(x = date,
y = value01,
group = variable)) %>%
ax_yaxis(decimalsInFloat = 2) %>%
ax_markers(size = c(3, 6)) %>%
ax_stroke(width = c(1, 3),
dashArray = c(8, 5))

Advanced configuration examples

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
mpg %>% 
count(class) %>%
mutate(pct = n / sum(n)) %>%
apex(aes(class, pct),
"column") %>%
ax_colors("#617a89") %>%
ax_yaxis(
title = list(text = "Weight (tons)"),
labels = list(
formatter = JS(
"function(value) {return Math.round(value * 100) + '%';}"
)
),
tickAmount = 6
) %>%
ax_xaxis(
title = list(text = "Fuel efficiency (mpg)")
) %>%
ax_tooltip(
title = list(
formatter = JS("function(){return 'Percentage';}")
)
) %>%
ax_labs(
title = "Seminal ggplot2 column chart example with percents",
subtitle = "Example taken from {hrbrthemes} readme"
) %>%
ax_title(
style = list(fontSize = "22px")
) %>%
ax_subtitle(
style = list(fontSize = "16px",
color = "#BDBDBD")
)

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
data("gapminder", package = "gapminder")

gapminder %>%
dplyr::filter(year == 2007) %>%
mutate(
gdpPercap = log(gdpPercap),
pop = sqrt(pop / pi) / 1500
) %>%
apex(mapping = aes(gdpPercap, lifeExp, z = pop, group = continent, label = country), type = "scatter") %>%
ax_chart(zoom = list(
enabled = TRUE, type = "xy"
)) %>%
ax_yaxis(
decimalsInFloat = 0,
axisBorder = list(show = TRUE),
axisTicks = list(show = TRUE),
title = list(text = "life expectancy at birth (in years)")
) %>%
ax_xaxis(
tickAmount = 8,
labels = list(
formatter = JS("function(val) {return val.toFixed(2);}")
),
tooltip = list(enabled = FALSE),
title = list(text = "GDP per capita (log-scale)")
) %>%
ax_grid(xaxis = list(lines = list(show = TRUE))) %>%
ax_legend(position = "right", offsetY = 70) %>%
ax_markers(hover = list(sizeOffset = 0, size = 25)) %>%
ax_tooltip(custom = JS(paste(
"function({ series, seriesIndex, dataPointIndex, w }) {",
"console.log(w); return (",
"'<div>' +",

"'<div class = \"apexcharts-tooltip-title\">' +",
"w.config.series[seriesIndex].data[dataPointIndex].label",
"+ '</div>' +",
"'<div style = \"padding: 5px;\">' +",
"'<div class = \"apexcharts-tooltip-y-group\">' +",

"'<span class = \"apexcharts-tooltip-text-label\">' +",
"'Population: ' +",
"'</span>' +",
"'<span class = \"apexcharts-tooltip-text-value\">' +",
"Math.round(Math.pow(w.config.series[seriesIndex].data[dataPointIndex].z * 1500, 2) * Math.PI).
toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\") +",
"'</span>' +",

"'</br>' +",

"'<span class = \"apexcharts-tooltip-text-label\">' +",
"'GDP per capita: ' +",
"'</span>' +",
"'<span class = \"apexcharts-tooltip-text-value\">' +",
"Math.round(Math.exp(w.config.series[seriesIndex].data[dataPointIndex].x)) +",
"'</span>' +",

"'</br>' +",

"'<span class = \"apexcharts-tooltip-text-label\">' +",
"'Life expectancy: ' +",
"'</span>' +",
"'<span class = \"apexcharts-tooltip-text-value\">' +",
"w.config.series[seriesIndex].data[dataPointIndex].y +",
"'</span>' +",


"'</div>' +",
"'</div>' +",

"'</div>'",
");",
"}", sep = "\n"
))) %>%
ax_labs(
title = "Life expectancy, GDP and population",
subtitle = "gapminder dataset from {gapminder}"
) %>%
ax_title(
style = list(fontSize = "22px")
) %>%
ax_subtitle(
style = list(fontSize = "16px", color = "#BDBDBD")
)

R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
data("vaccines", package = "highcharter")

apex(vaccines, aes(year, state, fill = count), type = "heatmap") %>%
ax_chart(animations = list(enabled = FALSE)) %>%
ax_dataLabels(enabled = FALSE) %>%
ax_stroke(width = 0) %>%
ax_plotOptions(
heatmap = heatmap_opts(
radius = 0,
enableShades = FALSE,
colorScale = list(
ranges = list(
list(
from = 0,
to = 0.001,
name = "Missing",
color = "#FFF"
),
list(
from = 0.001,
to = 4,
name = "low",
# color = "#000004"
color = "#FDE725"
),
list(
from = 4,
to = 70,
name = "mid-low",
# color = "#781C6D",
color = "#35B779"
),
list(
from = 70,
to = 290,
name = "mid-high",
# color = "#ED6925",
color = "#31688E"
),
list(
from = 290,
to = 3000,
name = "high",
# color = "#FCFFA4",
color = "#440154"
)
)
)
)
) %>%
ax_legend(
formatter = JS(
"function(seriesName, opts) {
if (seriesName == 'Missing') return null; else return seriesName;
}"
)
) %>%
ax_yaxis(
labels = list(
style = list(fontSize = "8px"),
offsetY = -20
)
) %>%
ax_annotations(
xaxis = list(
list(
x = 1963, x2 = 1963.1,
strokeDashArray = 0,
opacity = 1,
borderColor = "firebrick",
fillColor = "firebrick",
label = list(
borderColor = "firebrick",
style = list(color = "#FFF", background = "firebrick"),
text = "Vaccine Intoduced",
orientation = "horizontal",
position = "bottom",
offsetY = 10
)
)
)
) %>%
ax_labs(
title = "Infectious Diseases and Vaccines",
subtitle = "vaccines dataset from {highcharter}"
) %>%
ax_title(
style = list(fontSize = "22px")
) %>%
ax_subtitle(
style = list(fontSize = "16px", color = "#BDBDBD")
)

# R

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×