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:
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)
Try this if you want have legends too:
df <- rbind(data.frame(x=rnorm(2000, 0, 1), vec='1'),
data.frame(x=rnorm(3000, 1, 1.5), vec='2'))
ggplot(df, aes(x, group=vec, col=vec)) + geom_density(position='dodge')
I had some troubles with the the above solution, as my data was contained in a single data frame. Using ...
data=df$A
in the aesthetics doesn't work as this will provide ggplot with a vector of class "numeric", which isn't supported.
Therefor, to overlay different columns all contained in the same data frame, I'd suggest:
vec1 <- rnorm(3000, 0, 1)
vec2 <- rnorm(3000, 1, 1.5)
df <- data.frame(vec1, vec2)
colnames(df) <- c("A", "B")
library(ggplot2)
ggplot() + geom_density(aes(x=df$A), colour="red") +
geom_density(aes(x=df$B), colour="blue")
For most people this might seem obvious, but for me as a beginner, it wasn't. Hope this helps.