- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 create a horizontal line in ggplot2 graph with different color in R?
To create a horizontal line in ggplot2 graph with different in R, we can follow the below steps −
- First of all, create a data frame.
- Then, create a plot using ggplot2 using geom_hline function having horizontal line.
- After that, create the same plot with line color defined with col argument.
Create the data frame
Let's create a data frame as shown below −
x<-sample(1:100,20) y<-sample(1:1000,20) df<-data.frame(x,y) df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y 1 85 35 2 91 593 3 19 491 4 40 601 5 84 283 6 18 179 7 88 349 8 47 769 9 30 279 10 62 881 11 3 930 12 94 429 13 77 576 14 52 792 15 37 757 16 89 405 17 73 713 18 23 72 19 96 931 20 92 350
Create the plot with ggplot2
Using ggplot2 function to create the scatterplot between x and y with horizontal line at 600 −
x<-sample(1:100,20) y<-sample(1:1000,20) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=600)
Output
Create the plot with colored horizontal line
Using col argument inside geom_hline to create the colored horizontal line −
x<-sample(1:100,20) y<-sample(1:1000,20) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=600,col=2)
Output
- Related Articles
- How to create a horizontal line in ggplot2 graph with larger width in R?
- How to create a dashed horizontal line in a ggplot2 graph in R?
- How to create a wide vertical line using ggplot2 with different color in R?
- How to create a horizontal bar graph using ggplot2 in R?
- How to create line chart for categories with grey color palette using ggplot2 in R?
- How to create horizontal legend using ggplot2 in R?
- How to create a line chart using ggplot2 with a vertical line in R?
- How to create a bar graph using ggplot2 without horizontal gridlines and Y-axes labels in R?
- How to create a circle with different color border in R?
- How to create horizontal line in xyplot in R?
- How to create facetted plot with facets in horizontal direction using ggplot2 in R?
- How to create a scatterplot using ggplot2 with different shape and color of points based on a variable in R?
- How to change the plot border color of a ggplot2 graph in R?
- How to change the color of gridlines of a ggplot2 graph in R?
- How to create a ggplot2 graph in R without showing values?

Advertisements