Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add horizontal line to ggplot() for specified interval of x axis

Tags:

r

ggplot2

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?

like image 445
upabove Avatar asked Dec 01 '13 11:12

upabove


People also ask

How do I make a horizontal line in ggplot2?

Example: To add the horizontal line on the plot, we simply add geom_hline() function to ggplot2() function and pass the yintercept, which basically has a location on the Y axis, where we actually want to create a vertical line.

How do I insert a horizontal line in R?

The R function abline() can be used to add vertical, horizontal or regression lines to a graph. A simplified format of the abline() function is : abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)

What does %>% do in Ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

How do you add a vertical line in a graph in ggplot2?

To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a wide vertical line with different color then lwd and colour argument will be used. The lwd argument will increase the width of the line and obviously colour argument will change the color.


2 Answers

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

like image 179
Didzis Elferts Avatar answered Sep 27 '22 08:09

Didzis Elferts


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

like image 39
agstudy Avatar answered Sep 29 '22 08:09

agstudy