Add horizontal line to ggplot

I want to use ggplot2 to draw multiple lines with different colors in one graphic, and then add a separate horizontal line. My code is as follows. It works well until I run the final line p + geom_hline(yintercept=400). All lines turn black, and the legend on the right side disappears.

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)
+3
source share
2 answers

You do not save intermediate steps. Each plot adds only one thing to p. If you want to keep the part that you just added, you will need to do something like:

p <- p + geom_line(aes(colour = rating))
+6
source

p + geom_hline(yintercept=400), .

, p + geom_line(aes(colour = rating)) + geom_hline(yintercept=400). p + geom_line(aes(colour = rating)) + geom_hline(yintercept=400).

, , .

+2

All Articles