我试图用两个以上的组来创建高图表密度。我找到了一种手动手动添加它们的方法,但是必须有更好的方法来处理组。
示例:我想创建一个类似于下面的ggplot图表的高图,而不一一添加。有什么办法吗?
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)
答案 0 :(得分:0)
我无法在highcharter
中找到直接这样做的方法。但是,如果您事先计算密度并使用purrr
的{{1}}函数,则可以自动创建绘图:
reduce()
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
将所有其他密度添加到其中。
答案 1 :(得分:0)
方法1: tapply
+ reduce
+ hc_add_series
tapply(df$MEI, df$Region, density) %>%
reduce(.f = hc_add_series, .init = highchart())
方法2: 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)