- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to display a line in segment of a plot using ggplot2 in R?
To display a line in segment of a plot, we can use geom_segment function of ggplot2 package where we need to pass the initial and the ending values for both the axes. For example, if we have data frame called df that contains x and y then a scatterplot with a line segment can be created by using the below command −
ggplot(df,aes(x,y))+geom_point()+ geom_segment(aes(x=xstart,xend=xlast,y=ystart,yend=ylast))
Consider the below data frame −
Example
x<-rpois(20,5) y<-rpois(20,5) df<-data.frame(x,y) df
Output
x y 1 4 6 2 6 4 3 8 10 4 5 7 5 8 2 6 2 3 7 7 6 8 1 8 9 4 3 10 5 5 11 6 5 12 3 1 13 9 11 14 6 7 15 7 10 16 8 8 17 5 6 18 5 5 19 3 2 20 5 5
Loading ggplot2 package and creating a scatterplot of x and y −
Example
library(ggplot2) ggplot(df,aes(x,y))+geom_point()
Output
Creating a scatterplot of x and y with a line segment −
Example
ggplot(df,aes(x,y))+geom_point()+geom_segment(aes(x=1,xend=7,y=5,yend=8))
Output
- Related Articles
- How to display fraction in a plot title using ggplot2 in R?
- How to display regression slope using model in a plot created by ggplot2 in R?
- How to display regression intercept using model in a plot created by ggplot2 in R?
- How to create a dot plot using ggplot2 in R?
- How to display text in bar plot in the middle using ggplot2 in R?
- How to display average line for y variable using ggplot2 in R?
- How to create horizontal line for a range of values in a plot created by using ggplot2 in R?
- How to plot the regression line starting from origin using ggplot2 in R?
- How to display mean in a histogram using ggplot2 in R?
- How to display axes ticks and labels inside the plot using ggplot2 in R?
- How to display mean line per group in facetted graph using ggplot2 in R?
- How to add a horizontal line to the plot created by ggplot2 in R?
- How to reverse the bars of a bar plot a using ggplot2 in R?
- How to create a line chart using ggplot2 with a vertical line in R?
- How to change the border style of a plot using ggplot2 in R?

Advertisements