rmflight rmflight - 1 month ago 17
R Question

Overlapped density plots in ggplot2

Imagine I have two vectors each of different length. I want to generate one plot with the density of both vectors overlaid. What I thought I should do is this:

vec1 <- data.frame(x=rnorm(2000, 0, 1))
vec2 <- data.frame(x=rnorm(3000, 1, 1.5))
ggplot() + geom_density(aes(x=x, colour="red"), data=vec1) +
geom_density(aes(x=x, colour="blue"), data=vec2)


Then I thought I should do this:

vec1 <- data.frame(x=rnorm(2000, 0, 1))
vec2 <- data.frame(y=rnorm(3000, 1, 1.5))
ggplot() + geom_density(aes(x=x, colour="red"), data=vec1) +
geom_density(aes(x=y, colour="blue"), data=vec2)


Neither of these quite work, because the colors get mixed up.

Based on another solution I found in StackOverflow 1 2, I realized I should try this:

vec1 <- data.frame(x=rnorm(2000, 0, 1), grp="vec1")
vec2 <- data.frame(x=rnorm(3000, 1, 1.5), grp="vec2")
allDat <- rbind(vec1, vec2)

ggplot(allDat, aes(x, colour=grp)) + geom_density()

ggplot(allDat, aes(x, colour=grp)) + geom_density() +
scale_colour_manual(values=c("green", "blue"))

ggplot(allDat, aes(x, colour=grp)) + geom_density() +
scale_colour_manual(values=c(vec2="green", vec1="blue"))


OK, I solved my original problem. But is there a way to do something akin to the first one I tried above? From the way things are worded in the
ggplot
documentation, I would have thought so. Appreciate any suggestions.

Answer

Everything will work fine if you move the assignment of the colour parameter out of aes().

vec1 <- data.frame(x=rnorm(2000, 0, 1))
vec2 <- data.frame(x=rnorm(3000, 1, 1.5))

library(ggplot2)

ggplot() + geom_density(aes(x=x), colour="red", data=vec1) + 
  geom_density(aes(x=x), colour="blue", data=vec2)

enter image description here