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?
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.
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, ...)
%>% 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.
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.
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With