Question

I have three data sets of different lengths and I would like to plot density functions of all three on the same plot. This is straight forward with base graphics:

n <- c(rnorm(10000), rnorm(10000))
a <- c(rnorm(10001), rnorm(10001, 0, 2))
p <- c(rnorm(10002), rnorm(10002, 2, .5))

plot(density(n))
lines(density(a))
lines(density(p))

Which gives me something like this:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/10/density.png

But I really want to do this with GGPLOT2 because I want to add other features that are only available with GGPLOT2. It seems that GGPLOT really wants to take my empirical data and calculate the density for me. And it gives me a bunch of lip because my data sets are of different lengths. So how do I get these three densities to plot in GGPLOT2?

Was it helpful?

Solution

The secret to happiness in ggplot2 is to put everything in the "long" (or what I guess matrix oriented people would call "sparse") format:

df <- rbind(data.frame(x="n",value=n),
            data.frame(x="a",value=a),
            data.frame(x="p",value=p))
qplot(value, colour=x, data=df, geom="density")

If you don't want colors:

qplot(value, group=x, data=df, geom="density")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top