Highcharter

Author

Cody Paulay-Simmons

Working with HTML Widgets and Highcharter

Make a range of simple charts using the highcharter package

Highcharter is a package within the htmlwidgets framework that connects R to the Highcharts and Highstock JavaScript visualization libraries. For more information, see https://github.com/jbkunst/highcharter/

Also check out this site: https://cran.r-project.org/web/packages/highcharter/vignettes/charting-data-frames.html

Install and load required packages

Now install and load highcharter, plus RColorBrewer, which will make it possible to use ColorBrewer color palettes.

Also load dplyr and readr for loading and processing data.

# install highcharter
# load required packages
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.2     ✔ tibble    3.2.1
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.0.4     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(highcharter)
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo 
library(RColorBrewer)

Load and process nations data

Load the nations data, and add a column showing GDP in trillions of dollars.

nations <- read_csv("nations.csv") |>
  mutate(gdp_tn = gdp_percap*population/10^12)
Rows: 5275 Columns: 10
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (5): iso2c, iso3c, country, region, income
dbl (5): year, gdp_percap, population, birth_rate, neonat_mortal_rate

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Make a version of the “China’s rise” chart from unit 3 assignment

First, prepare the data using dplyr:

# prepare data
big4 <- nations |>
  filter(iso3c %in% c("CHN","DEU", "JPN", "USA")) |>
  arrange(year)

The arrange step is important, because highcharter needs the data in order when drawing a time series - otherwise any line drawn through the data will follow the path of the data order, not the correct time order.

Now draw a basic chart with default settings:

# basic symbol-and-line chart, default settings
highchart() |>
  hc_add_series(data = big4,
                type = "line", 
                hcaes(x = year,
                      y = gdp_tn, 
                      group = country))

In the code above, the function highchart() creates a chart.

Clicking on the legend items allows you to remove or add series from the chart.

Highcharts works by adding data “series” to a chart, and from R you can add the variables from a data frame all in one go using the hc_add_series function.

Inside this function we define the data frame to be used, with data, the type of chart, the variables to be mapped to the x and y axes, and the variable to group the data: here this draws a separate line for each country in the data.

Go to the github site provided above for the chart types available in Highcharts.

Now let’s begin customizing the chart.

Use a ColorBrewer palette

Using RColorBrewer, we can set a palette, and then use it in highcharter.

# define color palette
cols <- brewer.pal(4, "Set1")

highchart() |>
  hc_add_series(data = big4,
                type = "line", 
                hcaes(x = year,
                      y = gdp_tn, 
                      group = country)) |>
  hc_colors(cols)

The first line of code sets a palette with four colors, using the “Set1” palette from ColorBrewer. This is then fed to the function hc_colors() to use those colors on the chart.

Add axis labels

highchart() |>
  hc_add_series(data = big4,
                type = "line",
                hcaes(x = year,
                      y = gdp_tn,
                      group = country)) |>
  hc_colors(cols) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)"))

Change the legend position

For this, we use the hc_legend function.

highchart() |>
  hc_add_series(data = big4,
                   type = "line",
                   hcaes(x = year,
                         y = gdp_tn,
                         group = country)) |>
  hc_colors(cols) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)")) |>
  hc_plotOptions(series = list(marker = list(symbol = "circle"))) |>
  hc_legend(align = "right", 
            verticalAlign = "top")

Customize the tooltips

By default we have a tooltip for each series, or line, and the numbers run to many decimal places.

We can change to one tooltip for each year with “shared = TRUE”, and round all the numbers to two decimal places with pointFormat = “{point.country}: {point.gdp_tn:.2f}
.

# customize the tooltips

big4_chart <- highchart() |>
  hc_add_series(data = big4,
                type = "line",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = country)) |>
  hc_colors(cols) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)")) |>
  hc_plotOptions(series = list(marker = list(symbol = "circle"))) |>
  hc_legend(align = "right", 
            verticalAlign = "top") |>
  hc_tooltip(shared = TRUE,
             borderColor = "black",
             pointFormat = "{point.country}: {point.gdp_tn:.2f}")
big4_chart

Prepare the data

First, prepare the data using dplyr.

# prepare data
regions <- nations |>
  group_by(year,region) |>
  summarize(gdp_tn = sum(gdp_tn, na.rm = TRUE)) |>
  arrange(year,region)
`summarise()` has grouped output by 'year'. You can override using the
`.groups` argument.

Make an area chart using default options

# basic area chart, default options
highchart () |>
  hc_add_series(data = regions,
                type = "area",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = region))

This is an area chart, but the areas are plotted over one another, rather than stacked.

The following code fixes that, and customizes the chart in other ways. It uses the same ColorBrewer palette, with seven colors, that we used in unit 3.

# set color palette
cols <- brewer.pal(7, "Set2")

# stacked area chart
highchart () |>
  hc_add_series(data = regions,
                type = "area",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = region)) |>
  hc_colors(cols) |> 
  hc_chart(style = list(fontFamily = "Georgia",
                        fontWeight = "bold")) |>
  hc_plotOptions(series = list(stacking = "normal",
                               marker = list(enabled = FALSE,
                               states = list(hover = list(enabled = FALSE))),
                               lineWidth = 0.5,
                               lineColor = "white")) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)")) |>
  hc_legend(align = "right", verticalAlign = "top",
            layout = "vertical") 

We have already encountered the main functions used here. The key changes are in the hc_plotOptions() function:

stacking = “normal” creates the stacked chart. See what happens if you use stacking = “percent”.

lineWidth and lineColor set the width and color for the lines under marker = list() the code states = list(hover = list(enabled = FALSE)) turns off the hovering effect for each marker on the chart, so that the markers no longer reappear when hovered or tapped.

In the hc_legend() function, layout = “vertical” changes the layout so that the legend items appear in a vertical column.

Food Stamps Data - Combine Two Types

food_stamps<- read_csv("food_stamps.csv")
Rows: 47 Columns: 3
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
dbl (3): year, participants, costs

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
cols <- c("dodgerblue","orange")  # set the color palette to dodger blue and orange

highchart() |>
  hc_yAxis_multiples(
    list(title = list(text = "Participants (millions)")),
    list(title = list(text = "Costs ($ billions)"),
         opposite = TRUE)
  ) |>
  hc_add_series(data = food_stamps$participants,
                name = "Participants (millions)",
                type = "column",
                yAxis = 0) |>
  hc_add_series(data = food_stamps$costs,
                name = "Costs ($ billions)",
                type = "line",
                yAxis = 1) |>
  hc_xAxis(categories = food_stamps$year,
           tickInterval = 5) |>
  hc_colors(cols) |>
  hc_chart(style = list(fontFamily = "AvantGarde",
                        fontWeight = "bold"))