R Plotly overlay density & histogram

Sure - here’s an example:

library(plotly)

x <- rnorm(1000)
fit <- density(x)

plot_ly(x = x, type = "histogram", name = "Histogram") %>% 
  add_trace(x = fit$x, y = fit$y, mode = "lines", fill = "tozeroy", yaxis = "y2", name = "Density") %>% 
  layout(yaxis2 = list(overlaying = "y", side = "right"))

1 Like