Search code examples
rheatmapr-highcharter

Grouped categories for a highcharter heatmap in R


I'd like to create a heat map using the highercharter package and the open source gapminder dataset in R. However, I'm having difficulty creating an axis with grouped labels. Here is some code on creating a heat map from the highcharter documentation:

nyears <- 5
df <- expand.grid(seq(12) - 1, seq(nyears) - 1)
df$value <- abs(seq(nrow(df)) + 10 * rnorm(nrow(df))) + 10
df$value <- round(df$value, 2)
ds <- list_parse2(df)

hc <- highchart() %>%
  hc_chart(type = "heatmap") %>%
  hc_title(text = "Simulated values by years and months") %>%
  hc_xAxis(categories = month.abb) %>%
  hc_yAxis(categories = 2016 - nyears + seq(nyears)) %>%
  hc_add_series(name = "value", data = ds)
hc_colorAxis(hc, minColor = "#FFFFFF", maxColor = "#434348")

Now, let's say I have the following data:

for (package in c('tidyverse', 'gapminder')) {
  if (!require(package, character.only=T, quietly=T)) {
    install.packages(package)
    library(package, character.only=T)
  }
}

data(gapminder)
gapminder <- select(gapminder, continent, country, year, gdpPercap)

And here is my attempt:

gapminder <- select(gapminder, continent, country, year, gdpPercap)
gs <- list_parse2(gapminder)

categories_grouped <- gapminder %>%
  group_by(name = continent) %>% 
  do(categories = array(.$country)) %>% 
  list_parse()

highchart() %>%
  hc_chart(type = "heatmap") %>%
  hc_xAxis(categories = categories_grouped) %>%
  hc_yAxis(categories = gapminder$year) %>%
  hc_add_series(name = 'gdpPercap', data = gs)

Any idea of where I'm going wrong?


Solution

  • I guess you started your code with this example. Two things about the categories_grouped list,

    1. you need a 1-to-1 mapping, no redundancies, if you looked at the example, it started off from a dataframe of distinct class manufacturer.

    2. the sub elements of the list has to be named "name" and "categories"

    So first I select randomly 20 countries to plot, so that it can be seen clearly:

    library(gapminder)
    library(highcharter)
    library(dplyr)
    set.seed(100)
    x_country = sample(gapminder$country,20)
    
    dat<- select(gapminder, continent, country, year, gdpPercap) %>%
    filter(country %in% x_country) 
    
    dat=droplevels(dat)
    

    Now I create the categories grouped for the grouped x-axis:

    categories_grouped <- dat %>%
      distinct(continent,country) %>% 
      rename( name =continent) %>%
      group_by(name) %>%
      do(categories = .$country) %>% 
      list_parse()
    

    Now I plot, I seldom used a list, so I go with the setting below, should be ok:

    hc <-highchart() %>%
    hc_yAxis(categories = dat$year) %>%
    hc_xAxis(categories = categories_grouped) %>%
    hc_add_series(data = dat,type = 'heatmap',hcaes(x=country,y=factor(year),value=gdpPercap))
    
    hc_colorAxis(hc, minColor = "#FFFFFF", maxColor = "#434348")
    

    enter image description here