R Highcharter中的密度图

时间:2019-07-05 15:14:46

标签: r ggplot2 highcharts ggplotly r-highcharter

我正在尝试在highcharter R中绘制相似的密度图。我是highcharter的新手,任何指导将不胜感激。

dt <- data.frame(x=rnorm(1000),y=sample(c(0,1),size = 1000,replace = T))
library(ggplot2)
ggplot(data = dt) +
  aes(x = x,fill=factor(y)) +
  geom_density(adjust = 1,alpha=0.5) 

我的尝试:

library(highcharter)
library(dplyr)
hcdensity(density(dt$x), area = TRUE) %>% 
  hc_add_series(density(dt$y), area = TRUE)

1 个答案:

答案 0 :(得分:1)

您似乎想要两条曲线(y = 0和y = 1)。只会调用dt $ x的hcdensity,首先是y = 0。然后对于y = 1,对hc_add_series使用'density'。使用type ='area'填充。

hcdensity(dt$x[dt$y==0]) %>% 
  hc_add_series(density(dt$x[dt$y==1]), type='area')

如果要包含多条曲线或更通用的解决方案,请尝试以下操作:

library(purrr)
tapply(dt$x, dt$y, density) %>%
  reduce(.f = hc_add_series, type='area', .init=highchart())

这很有帮助:

Create highchart density with more than 2 groups