- 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 average line for y variable using ggplot2 in R?
To display the average line for y variable using ggplot2, we can use geom_hline function along with the yintercept. In the yintercept, we would need to calculate the mean of the y variable and we can also change the colour of the line using color argument inside the geom_hline function.
Example
Consider the below data frame −
> x<-rnorm(20) > y<-rnorm(20) > df<-data.frame(x,y) > df
Output
x y 1 -1.07323904 0.368641641 2 0.92531148 -0.196530651 3 -0.57433739 0.710957804 4 1.17367100 0.300110517 5 0.00769624 -1.287517035 6 0.64901161 -0.476105351 7 0.70197701 -0.683592585 8 -0.80807441 -1.716264317 9 0.10827026 0.116964308 10 -1.10451308 0.660382307 11 -0.01612692 -1.182533283 12 2.20292198 -1.890223763 13 -1.03368161 -0.526983486 14 0.24688341 -0.709657125 15 0.46439214 -0.611872054 16 -0.86472988 0.100839958 17 -1.29702868 -0.178357498 18 -1.51781901 0.006079342 19 0.03744727 -1.062274129 20 -1.62755835 -1.532681680
Loading ggplot2 package and creating a point chart between x and y −
> library(ggplot2) > ggplot(df,aes(x,y))+geom_point()
Output
Creating the point chart between x and y with average line for y −
> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=mean(y),color="red")
Output
- Related Articles
- How to display count on Y-axis for line chart using ggplot2 in R?
- How to display 0 at Y-axis using ggplot2 in R?
- How to display Y-axis with Euro sign using ggplot2 in R?
- How to display a variable with subscript ggplot2 graph in R?
- How to display a line in segment of a plot using ggplot2 in R?
- How to display mean line per group in facetted graph using ggplot2 in R?
- How to display positive sign for X-axis labels in R using ggplot2?
- How to create horizontal line for Y variable at median in base R plot?
- How to display mean for each group in point chart using ggplot2 in R?
- How to display two equal signs in R using ggplot2?
- How to display legend on top using ggplot2 in R?
- How to create different Y-axis for group levels using ggplot2 in R?
- How to display NA frequency for a ggplot2 graph using color brewer in R?
- How to display mean in a histogram using ggplot2 in R?
- How to create a boxplot using ggplot2 for single variable without X-axis labels in R?

Advertisements