R 中 highcharter 热图的分组类别

Grouped categories for a highcharter heatmap in R

我想创建一个 heat map using the highercharter package and the open source gapminder dataset in R. However, I'm having difficulty creating an axis with 。以下是 highcharter 文档中有关创建热图的一些代码:

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")

现在,假设我有以下数据:

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)

这是我的尝试:

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)

知道我哪里出错了吗?

我猜你的代码是从 this example 开始的。关于 categories_grouped 列表的两件事,

  1. 你需要一对一的映射,没有冗余,如果你看这个例子,它是从不同的 class 制造商的数据帧开始的。

  2. 列表的子元素必须命名为 "name" 和 "categories"

所以我先select随机画了20个国家,这样可以看得清楚:

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)

现在我为分组的 x 轴创建分组的类别:

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

现在画图,很少用list,所以按照下面的设置,应该可以的:

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")