✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.

# geom_density in ggplot2

Add a smooth density estimate calculated by stat_density with ggplot2 and R. Examples, tutorials, and code.

New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

### 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)

p <- ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)

fig <- ggplotly(p)

fig


### Stacked Density Plot

library(plotly)
set.seed(123)

df <- data.frame(x <- rchisq(1000, 5, 10),
group <-  sample(LETTERS[1:5], size = 1000, replace = T))

p <- ggplot(df, aes(x, fill = group)) +
geom_density(alpha = 0.5, position = "stack") +
ggtitle("stacked density chart")

fig <- ggplotly(p)

fig