16
votes

I would like to add horizontal lines to an existing plot, but I would only like to plot the line for certain intervals of the x-axis.

For example I would like to have a horizontal line at X=1:5 and y=50.

I would use existing_plot+geom_hline(yintercept = 50)

Is it also possible to specify the x values somehow?

2

2 Answers

32
votes

You can use geom_segment() to add line segment with your own defined starting and ending points (not only horizontal/vertical lines).

ggplot(mtcars,aes(mpg,qsec))+geom_point()+
  geom_segment(aes(x=15,xend=20,y=18,yend=18))

enter image description here

8
votes

You can use geom_line:

qplot(x=x,y=y,data=data.frame(x=1:10,y=100:1)) +
  geom_line(data=data.frame(x=1:5,y=50))

enter image description here