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

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With