使用 2 个以上的组创建高图表密度

Create highchart density with more than 2 groups

我试图创建具有两个以上组的高图表密度。我找到了一种手动添加它们的方法,但必须有更好的方法来处理组。

示例:我想创建一个类似于下面的 ggplot 图表的 highchart,而不是将它们一一添加。有什么办法吗?

d

f <- data.frame(MEI = c(-2.031, -1.999, -1.945, -1.944, -1.875, 
                       -1.873, -1.846, -2.031, -1.999, -1.945, -1.944, -1.875, -1.873, 
                       -1.846, -2.031, -1.999, -1.945, -1.944, -1.875, -1.873, -1.846, 
                       -2.031, -1.999, -1.945, -1.944, -1.875, -1.873, -1.846), 
                 Count = c(10L,0L, 15L, 1L, 6L, 10L, 18L, 10L, 0L, 15L, 1L, 6L, 10L, 0L, 15L, 
                          10L, 0L, 15L, 1L, 6L, 10L, 10L, 0L, 15L, 1L, 6L, 10L, 18L), 
                 Region = c("MidWest", "MidWest", "MidWest", "MidWest", "MidWest", "MidWest", "MidWest", 
                                        "South", "South", "South", "South", "South", "South", "South", 
                                        "South", "South", "South", "NorthEast", "NorthEast", "NorthEast", 
                                        "NorthEast", "NorthEast", "NorthEast", "NorthEast", "NorthEast", 
                                        "NorthEast", "NorthEast", "NorthEast"))
df <- data.table(ddf)
df %>%ggplot() + 
  geom_density(aes(x=MEI, group=Region, fill=Region),alpha=0.5) + 
  xlab("MEI") +
  ylab("Density")

hcdensity(df[Region=="NorthEast"]$MEI,area = TRUE) %>%
  hc_add_series(density(df[Region=="MidWest"]$MEI), area = TRUE) %>%
  hc_add_series(density(df[Region=="South"]$MEI), area = TRUE)

我无法在 highcharter 中找到直接这样做的方法。但是,如果您预先计算密度并使用 purrrreduce() 函数,您可以自动创建绘图:

library(purrr)

# calculate a list of densities (one per region)
densities <- df %>% group_by(Region) %>% 
  do(den = density(.$MEI)) %>%
  .$den

# create the highchart with all densities
reduce(densities, hc_add_series, .init = highchart())

reduce() 将列表组合成一个对象。对列表中的第一个密度应用 highchart(),从而创建必要的 highchart htmlwidget。然后将所有其他密度添加到 hc_add_series().

方法一:tapply+reduce+hc_add_series

tapply(df$MEI, df$Region, density) %>%
  reduce(.f = hc_add_series, .init = highchart())

方法二:map+hc_add_series_list

(参考:RPubs - Highcharter hc_add_series_list

ds <- map(levels(df$Region), function(x){
  dt <- density(df$MEI[df$Region == x])[1:2]
  dt <- list_parse2(as.data.frame(dt))
  list(data = dt, name = x)
})

highchart() %>% 
  hc_add_series_list(ds)