ggplot2: Plotting two or more overlapping density plots on the same graph

One R Tip A Day uses a custom R function to plot two or more overlapping density plots on the same graph.

http://learnr.files.wordpress.com/2009/03/3densities.gif?w=400&h=400

The same can be very easily accomplished in ggplot2.

 

> library(ggplot2)

Create dummy dataframe:

> df <- data.frame(x = rnorm(1000, 0, 1), y = rnorm(1000,
     0, 2), z = rnorm(1000, 2, 1.5))

“Melt” data:

> df.m <- melt(df)

Default plot:

> ggplot(df.m) + geom_freqpoly(aes(x = value,
     y = ..density.., colour = variable))
http://learnr.files.wordpress.com/2009/03/density3.png?w=416&h=415

Default plot + few formatting adjustments:

> ggplot(df.m) + geom_freqpoly(aes(x = value,
     y = ..density.., colour = variable)) +
     labs(x = NULL) + opts(legend.position = "none") +
     opts(title = "Frequency Polygons (based on binned counts)")
http://learnr.files.wordpress.com/2009/03/density11.png?w=416&h=415

Update: Hadley kindly points out that the above plots are frequency polygons. I have updated the post with a “real” density plot.

> ggplot(df.m) + geom_density(aes(x = value,
     colour = variable)) + labs(x = NULL) +
     opts(legend.position = "none") + opts(title = "Densities from a kernel density estimator")
http://learnr.files.wordpress.com/2009/03/density2.png?w=416&h=415