Distplots in ggplot2

How to make Distplots in ggplot2 with Plotly.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.

Note: We are retiring documentation for R, MATLAB, Julia, and F#. Learn more about this change here.

Basic Density Plot

library(plotly)

library(ggplot2)
set.seed(1234)

dfGamma = data.frame(nu75 = rgamma(100, 0.75),
           nu1 = rgamma(100, 1),
           nu2 = rgamma(100, 2))

dfGamma = stack(dfGamma)

p <- ggplot(dfGamma, aes(x = values)) +
  stat_density(aes(group = ind, color = ind),position="identity",geom="line")

fig <- ggplotly(p)

fig

Density & Facet

library(plotly)

require(plyr)
dd<-data.frame(matrix(rnorm(144, mean=2, sd=2),72,2),c(rep("A",24),rep("B",24),rep("C",24)))
colnames(dd) <- c("x_value", "Predicted_value",  "State_CD")

dd <- data.frame(
  predicted = rnorm(72, mean = 2, sd = 2),
  state = rep(c("A", "B", "C"), each = 24)
)

grid <- with(dd, seq(min(predicted), max(predicted), length = 100))
normaldens <- ddply(dd, "state", function(df) {
  data.frame(
    predicted = grid,
    density = dnorm(grid, mean(df$predicted), sd(df$predicted))
  )
})

p <- ggplot(dd, aes(predicted))  +
  geom_density() +
  geom_line(aes(y = density), data = normaldens, colour = "red") +
  facet_wrap(~ state)

fig <- ggplotly(p)

fig

Multiple Density Plot

library(plotly)

carrots <- data.frame(length = rnorm(100000, 6, 2))
cukes <- data.frame(length = rnorm(50000, 7, 2.5))

#Now, combine your two dataframes into one.  First make a new column in each.
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'

#and combine into your new data frame vegLengths
vegLengths <- rbind(carrots, cukes)

#now make your lovely plot
p <- ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)

fig <- ggplotly(p)

fig