gpt4 book ai didi

r - 使用 2 个以上的组创建 Highcharts 密度

转载 作者:行者123 更新时间:2023-12-04 11:46:24 27 4
gpt4 key购买 nike

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

示例:我想创建一个类似于下面的 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)

最佳答案

方法一: 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)

enter image description here

关于r - 使用 2 个以上的组创建 Highcharts 密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53929991/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com