0

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)
Rushabh Patel
  • 2,672
  • 13
  • 34
  • can you describe a bit more the problems you are having with density plots in highcharter? or what is the final expected outcome you desire? – Ben Jul 06 '19 at 18:38
  • I assume that you want to display area chart. Both or your codes (ggplot and highcharter) work fine. Please, explain what is the problem and what do you want to achieve. Do you have any specific question? – raf18seb Jul 08 '19 at 08:31
  • @Ben I am expecting similar output using Highcharter (code chunk 2) which I am obtaining from ggplot (code chunk 1). – Rushabh Patel Jul 08 '19 at 14:05

1 Answers1

1

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:

Create highchart density with more than 2 groups

Ben
  • 28,684
  • 5
  • 23
  • 45