Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create highchart density with more than 2 groups

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)
like image 447
southwind Avatar asked Sep 11 '26 12:09

southwind


1 Answers

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)

enter image description here

like image 82
Darren Tsai Avatar answered Sep 14 '26 02:09

Darren Tsai