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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With