Create highchart density with more than 2 groups

爱⌒轻易说出口 提交于 2020-01-24 10:04:25

问题


I tried to create highchart density with more than two groups. I found a way to add them one by one manually but there must be a better way to handle groups.

Examples: I would like to create a highchart similar to ggplot chart below without adding them one by one. Is there any way to do so?

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)

回答1:


Method 1: tapply + reduce + hc_add_series

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

Method 2: map + hc_add_series_list

(Reference: 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)




回答2:


I couldn't figure out a way to do so directly in highcharter. But if you calculate the densities beforehand and use purrr's reduce() function you can automatize the plot creation:

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() combines the list into a single object. To the first density in the list highchart() is applied and thus the necessary highchart htmlwidget is created. All the other densities are then added to it with hc_add_series().



来源:https://stackoverflow.com/questions/53929991/create-highchart-density-with-more-than-2-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!