Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overlay density plots in R?

I would like to overlay 2 density plots on the same device with R. How can I do that? I searched the web but I didn't find any obvious solution.

My idea would be to read data from a text file (columns) and then use

plot(density(MyData$Column1)) plot(density(MyData$Column2), add=T) 

Or something in this spirit.

like image 916
pasta Avatar asked Aug 04 '11 09:08

pasta


People also ask

How do you plot a density plot in R?

To create a density plot in R you can plot the object created with the R density function, that will plot a density curve in a new R window. You can also overlay the density curve over an R histogram with the lines function. The result is the empirical density function.


2 Answers

use lines for the second one:

plot(density(MyData$Column1)) lines(density(MyData$Column2)) 

make sure the limits of the first plot are suitable, though.

like image 172
cbeleites unhappy with SX Avatar answered Sep 21 '22 23:09

cbeleites unhappy with SX


ggplot2 is another graphics package that handles things like the range issue Gavin mentions in a pretty slick way. It also handles auto generating appropriate legends and just generally has a more polished feel in my opinion out of the box with less manual manipulation.

library(ggplot2)  #Sample data dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))                    , lines = rep(c("a", "b"), each = 100)) #Plot. ggplot(dat, aes(x = dens, fill = lines)) + geom_density(alpha = 0.5) 

enter image description here

like image 21
Chase Avatar answered Sep 22 '22 23:09

Chase