Add A Horizontal Line To Plot And Legend In Ggplot2


Answer :

(1) Try this:

cutoff <- data.frame( x = c(-Inf, Inf), y = 50, cutoff = factor(50) ) ggplot(the.data, aes( year, value ) ) +          geom_point(aes( colour = source )) +          geom_smooth(aes( group = 1 )) +          geom_line(aes( x, y, linetype = cutoff ), cutoff) 

screenshot

(2) Regarding your comment, if you don't want the cutoff listed as a separate legend it would be easier to just label the cutoff line right on the plot:

ggplot(the.data, aes( year, value ) ) +      geom_point(aes( colour = source )) +      geom_smooth(aes( group = 1 )) +      geom_hline(yintercept = 50) +      annotate("text", min(the.data$year), 50, vjust = -1, label = "Cutoff") 

screenshot

Update

This seems even better and generalizes to mulitple lines as shown:

line.data <- data.frame(yintercept = c(50, 60), Lines = c("lower", "upper")) ggplot(the.data, aes( year, value ) ) +          geom_point(aes( colour = source )) +          geom_smooth(aes( group = 1 )) +          geom_hline(aes(yintercept = yintercept, linetype = Lines), line.data) 

Another solution :

gg <- ggplot(the.data, aes( x = year, y = value ) ) +          geom_point(aes(colour = source)) +          geom_smooth(aes(group = 1))  cutoff <- data.frame(yintercept=50, cutoff=factor(50)) gg +    geom_hline(aes(yintercept=yintercept, linetype=cutoff), data=cutoff, show_guide=TRUE)  

This code generates exactly the same graphic as the one in point (1) of @G. Grothendieck. But it is more easy to adapt to graphics with several layers.


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Change The Font Size Of Visual Studio Solution Explorer