Reputation: 355
I want to use ggplot2 to draw multiple line with different colors in one plot and then add a separate horizontal line. My code is as below. It works well until I run the final line p + geom_hline(yintercept=400)
. All the lines become black and legend on the right side disappear.
Does anyone know how to solve this problem?
library(ggplot2)
mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
nums <- tapply(df$length, df$year, length)
data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)),
number=as.vector(nums))
}))
p<-qplot(year, number, data=mry, group=rating, geom="line",xlab = 'year',
ylab = 'number')
p + geom_line()
p + geom_line(aes(colour = rating))
p + geom_hline(yintercept=400)
Upvotes: 4
Views: 17737
Reputation: 7928
A concrete solution to your question above could be to simply move your last line of code, p + geom_hline(yintercept=400)
, up to be part of the second to last line.
This would make your last line of code look like this, p + geom_line(aes(colour = rating)) + geom_hline(yintercept=400)
. You could also combine your three last lines into p + geom_line(aes(colour = rating)) + geom_hline(yintercept=400)
.
Basically restating what joran suggests, but I'm trying to make it more concrete.
Upvotes: 2
Reputation: 173527
You're not saving the intermediate steps. Each plot is adding just that one thing to p
. If you want to keep the piece you just added, you'd need to do something like:
p <- p + geom_line(aes(colour = rating))
Upvotes: 7