Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

r - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...