In this article, we will see how to add Vertical and Horizontal lines to the plot using ggplot2 in R Programming Language.
Adding Vertical Line To R Plot using geom_vline()
For adding the Vertical line to the R plot, geom_vline() draws a vertical line at a specified position.
Parameter: here xintercept is used control the X position of line.
Return: Vertical line on R plot.
Example: To add the vertical line on the plot, we simply add geom_vline() function to ggplot2() function and pass the xintercept, which basically has a location on X-axis, where we actually want to create a vertical line. Here we set 2011 to the xintercept.
Adding Horizontal Line To R Plot using geom_hline()
And for adding Horizontal lines to the R plot, we will use geom_hline() function:
Parameter: here yintercept is used control the y position of line.
Return: Horizontal line on R plot.
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. Here we set 20 to the xintercept.
Adding both vertical and horizontal lines to R plot
To add both lines, we add both geom_vline() and geom_hline() function to ggplot() function and set the values of xintercept and yintercept.
Example: Here we will draw the vertical line at X=2012 and the vertical line at Y=20.
Adding multiple vertical and horizontal lines to R plot using seq() function
We will use seq() function to represent the xintercept and yintercept and all other settings will remain the same as example 3.
Syntax: seq(from, to, by)
- from : it is used to represent starting length.
- to: it is used to represent ending length.
- by: it represents increment of the system.
Return: well-formed sequence.
Example: Here we’re drawing vertical lines from 2011 to 2015 with a difference of 0.5 and horizontal lines from 10 to 50 with a difference of 5.