Highcharts is a JavaScript charting library that creates interactive
visualizations. The highcharter
package integrates this
functionality into R, allowing us to produce dynamic plots easily.
Note: To experience the interactive features, such as the range selector, knit this document to HTML. Static formats like PDF or Word will only show static images.
First we will create a simple scatterplot using the
penguins
dataset from the palmerpenguins
package. Notice how easy it is to create an interactive scatterplot with
highcharter
. The hchart()
function is used to
create the chart, and hcaes()
is used to specify the
aesthetics (x and y axes, and grouping variable).
data(penguins, package = "palmerpenguins")
hchart(
penguins,
"scatter",
hcaes(x = flipper_length_mm, y = bill_length_mm, group = species)
)
data(economics_long, package = "ggplot2")
economics_long2 <- dplyr::filter(economics_long, variable %in% c("pop", "uempmed", "unemploy"))
hchart(economics_long2, "line",
hcaes(x = date, y = value01, group = variable))
We’ll use the economics
dataset from
ggplot2
, which contains monthly U.S. economic indicators
from July 1967 to 2015.
This line chart visualizes the median duration of unemployment
(uempmed
) in weeks, also with a range selector.
data(economics)
hchart(economics, "line", hcaes(x = date, y = uempmed)) %>%
hc_title(text = "Median Duration of Unemployment Over Time") %>%
hc_xAxis(type = "datetime", title = list(text = "Date")) %>%
hc_yAxis(title = list(text = "Median Duration (weeks)")) %>%
hc_rangeSelector(
enabled = TRUE,
buttons = list(
list(type = "year", count = 1, text = "1y"),
list(type = "year", count = 5, text = "5y"),
list(type = "year", count = 10, text = "10y"),
list(type = "all", text = "All")
),
inputEnabled = TRUE
)
#summary(air_passengers)
airforecast <- forecast(auto.arima(AirPassengers), level = 95)
hchart(airforecast)
Let’s try an interactive multiple line chart of life expectancy over time for selected countries.
# Select countries for the chart
countries <- c("United States", "China", "Japan", "Germany", "India")
# Filter the gapminder dataset for selected countries
gapminder_filtered <- gapminder %>% filter(country %in% countries)
# Create the interactive line chart
hchart(gapminder_filtered, "line", hcaes(x = year, y = lifeExp, group = country)) %>%
hc_title(text = "Life Expectancy Over Time by Country") %>%
hc_xAxis(title = list(text = "Year")) %>%
hc_yAxis(title = list(text = "Life Expectancy (years)")) %>%
hc_plotOptions(line = list(
lineWidth = 1, # Default thin lines
marker = list(enabled = FALSE), # No markers for cleaner look
states = list(
hover = list(
enabled = TRUE,
lineWidthPlus = 3 # Thicken line on hover
),
inactive = list(
opacity = 0.1 # Fade other lines
)
)
)) %>%
hc_tooltip(pointFormat = "{series.name}: {point.y} years") # Custom tooltip
x <- c(rnorm(10000), rnorm(1000, 4, 0.5))
hchart(x, name = "data", color = "steelblue") %>%
hc_title(text = "Histogram of Random Data") %>%
hc_xAxis(title = list(text = "Value")) %>%
hc_yAxis(title = list(text = "Frequency")) %>%
hc_plotOptions(column = list(
pointPadding = 0.2,
borderWidth = 0
)) %>%
hc_tooltip(pointFormat = "Value: {point.x}<br>Frequency: {point.y}")
This bar chart displays the average personal savings rate by decade, with the savings rate shown to one decimal place in the tooltip.
First, we prepare the data by calculating the average savings rate for each decade.
We divide a given year by 10, round it down, then multiply back by 10
to group by the start of the decade in order to calculate the average
personal savings rate (psavert
).
data(economics)
economics_decade <- economics %>%
mutate(decade = floor(year(date) / 10) * 10) %>%
group_by(decade) %>%
summarize(avg_psavert = mean(psavert, na.rm = TRUE))
Then, we create the bar chart with a formatted tooltip.
hchart(economics_decade, "column", hcaes(x = decade, y = avg_psavert)) %>%
hc_title(text = "Average Personal Savings Rate by Decade") %>%
hc_xAxis(title = list(text = "Decade")) %>%
hc_yAxis(title = list(text = "Average Savings Rate (%)")) %>%
hc_tooltip(pointFormat = "Decade: {point.x}<br>Avg Savings Rate: {point.y:.1f}%")
x <- getSymbols("GOOG", auto.assign = FALSE)
highchart(type = "stock") |>
hc_add_series(x)
This pie chart shows the distribution of median unemployment duration categories over the entire period from 1967 to 2015. Each slice represents the proportion of months where the median unemployment duration fell into a specific range.
First, we categorize the median unemployment duration
(uempmed
) into bins and count the number of months in each
category.
# Prepare data for pie chart
economics_pie <- economics %>%
mutate(duration_cat = cut(uempmed,
breaks = c(0, 5, 10, 15, 20, Inf),
labels = c("<5 weeks", "5-10 weeks", "10-15 weeks", "15-20 weeks", "20+ weeks"),
right = FALSE)) %>%
count(duration_cat)
Then, we create the interactive pie chart.
# Create the pie chart
hchart(economics_pie, "pie", hcaes(name = duration_cat, y = n)) %>%
hc_title(text = "Distribution of Median Unemployment Duration Categories") %>%
hc_subtitle(text = "Based on monthly data from 1967 to 2015") %>%
hc_plotOptions(pie = list(
allowPointSelect = TRUE,
cursor = "pointer",
dataLabels = list(enabled = TRUE, format = "{point.percentage:.1f}%")
)) %>%
hc_tooltip(pointFormat = "{point.name}: {point.y} months ({point.percentage:.1f}%)")
dfdiam <- diamonds |>
group_by(cut, clarity) |>
summarize(price = median(price))
hchart(dfdiam, "heatmap", hcaes(x = cut, y = clarity, value = price), name = "Median Price")