I am trying to plot similar density plot in highcharter R
. I am pretty new to highcharter
, any guidance will be really appreciated.
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)
My Attempts:
library(highcharter)
library(dplyr)
hcdensity(density(dt$x), area = TRUE) %>%
hc_add_series(density(dt$y), area = TRUE)
It looks like you want two curves (y = 0 and y = 1). Would just call hcdensity of dt$x, first for y=0. Then for y=1 use 'density' for hc_add_series. Use type='area' to fill.
hcdensity(dt$x[dt$y==0]) %>%
hc_add_series(density(dt$x[dt$y==1]), type='area')
If you want to include multiple curves or more generalizable solution, try this:
library(purrr)
tapply(dt$x, dt$y, density) %>%
reduce(.f = hc_add_series, type='area', .init=highchart())
This was helpful: