Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
How to plot a dashed line in matplotlib?
Next article icon

How to Add an Average Line to Plot in Matplotlib

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how we can add an average line to a plot in matplotlib. We will discuss the steps to add a horizontal average line using the axhline function, as well as the steps to add a vertical average line using the axvline function in Matplotlib. Throughout the article, we will use examples and code so that you can easily implement the learnings.

Adding a Horizontal Average Line to a Plot in Matplotlib

Before we begin with adding an average line to a plot in Matplotlib, let us first prepare a sample Matplotlib scatterplot. Here is the code for the same:

Python3
#import pandas import matplotlib.pyplot as plt import pandas as pd  # prepare the dataframe df = pd.DataFrame({'x': [2, 4, 5, 7, 9, 10, 11, 13, 14, 16],                    'y': [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9]})  # import pyplot from matplotlib  # create scatter plot plt.scatter(df.x, df.y)  # see the plot plt.show() 

Output:

output-1
output

Now, we can use the following piece of code to add a horizontal average line to the plot:

Python3
#import numpy  import numpy as np  #add horizontal average line  plt.axhline(y=np.nanmean(df.y)) 

Here is the complete code to add an average line to a plot in matplotlib:

Python3
#import pandas  import pandas as pd  #import numpy  import numpy as np  #prepare the dataframe df = pd.DataFrame({'x' : [2, 4, 5, 7, 9, 10, 11, 13, 14, 16],                    'y' : [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9]})  #import pyplot from matplotlib  import matplotlib.pyplot as plt   #create scatter plot  plt.scatter(df.x, df.y)  #add horizontal average line  plt.axhline(y=np.nanmean(df.y))  #see the plot  plt.show() 

Output:

output-2
output


You can see that the line is drawn at the mean of all values of Y axis, that is 1. You can use this Python code to check the mean of the values on the Y axis:

Python3
print(np.nanmean(df.y)) 

Output:

1.0

Let us now understand how the code for adding the horizontal line works. The code has two main functions, axhline and nanmean. Let us look at them in detail.

The axhline function

The axhline function stands for axis horizontal line and as per its name, it draws a horizontal line on the plot across the axes.

Python3
matplotlib.pyplot.axhline(y=0, xmin=0, xmax=1, **kwargs)  


In the code, we have passed only one argument that gives the y position of the line. You can further use other parameters to change the line color, style, and width of the line. Here is the code and corresponding output for the same:

Python3
#import pandas  import pandas as pd  #import numpy  import numpy as np  #prepare the dataframe df = pd.DataFrame({'x' : [2, 4, 5, 7, 9, 10, 11, 13, 14, 16],                    'y' : [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9]})  #import pyplot from matplotlib  import matplotlib.pyplot as plt   #create scatter plot  plt.scatter(df.x, df.y)  #add horizontal average line  plt.axhline(   y=np.nanmean(df.y),    color = 'g',   linestyle = '--',    linewidth = 3 )  #see the plot  plt.show() 

Output



output-3
output


You can see that this time, the horizontal average line is green in colour and dotted in style. It is also a lot thicker than usual. You can learn more about the axhline function here.

The nanmean function

The nanmean function is used to calculate the average for a given data. The term 'nan' in the nanmean function signifies that this function takes care of NAN or Not a number values as well.

Python3
numpy.nanmean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>) 

In our code, we have only passed one parameter, i.e, 'df.y' to pass the y coordinates of the data.

If your data has no NAN values, then you can simply use the mean() function as follows:

Python3
#add horizontal average line  plt.axhline(y=np.mean(df.y)) 


Adding a Vertical Average Line to a Plot in Matplotlib

You can also add an average line in a plot in matplotlib vertically, i.e, along the y axis.

To add a vertical average line in a plot in matplotlib, you simply have to use the axvline function instead of the axhline function. Further, we will need to find the average of values along the x axis this time, so we will use 'x.np.nanmean(df.x)' as the argument for axvline function.

Here is the code for the same:

Python3
#import pandas  import pandas as pd  #import numpy  import numpy as np  #prepare the dataframe df = pd.DataFrame({'x' : [2, 4, 5, 7, 9, 10, 11, 13, 14, 16],                    'y' : [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9]})  #import pyplot from matplotlib  import matplotlib.pyplot as plt   #create scatter plot  plt.scatter(df.x, df.y)  #add vertical average line  plt.axvline(x=np.nanmean(df.x))  #see the plot  plt.show() 

Output :



output
output


Let us now understand the axvline function in detail.

The axvline function

The axvline function as the name suggests, draws a vertical line along the axis.

Python3
matplotlib.pyplot.axvline(x=0, ymin=0, ymax=1, **kwargs) 

In the code, we have passed only one argument that gives the x position of the line. You can further use other parameters just like we did with axhline function, to change the line color, style, and width of the line. Here is the code and corresponding output for the same:

Python3
#import pandas  import pandas as pd  #import numpy  import numpy as np  #prepare the dataframe df = pd.DataFrame({'x' : [2, 4, 5, 7, 9, 10, 11, 13, 14, 16],                    'y' : [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9]})  #import pyplot from matplotlib  import matplotlib.pyplot as plt   #create scatter plot  plt.scatter(df.x, df.y)  #add vertical average line  plt.axvline(   x=np.nanmean(df.x),    color = 'g',   linestyle = '--',    linewidth = 3 )  #see the plot  plt.show() 

Output:

output5
output

In this post, we learned how we can add an average line to a plot in matplotlib. You can use different functions from the matplotlib library of Python to add a horizontal as well as a vertical line to a plot in matplotlib. Further, you can change how the line appears by using the parameters provided with the axhline and axvline functions.



Next Article
How to plot a dashed line in matplotlib?

E

everythingtech
Improve
Article Tags :
  • Machine Learning
  • Geeks Premier League
  • AI-ML-DS
  • Geeks Premier League 2023
Practice Tags :
  • Machine Learning

Similar Reads

  • How to plot a dashed line in matplotlib?
    Matplotlib is used to create visualizations and plotting dashed lines is used to enhance the style and readability of graphs. A dashed line can represent trends, relationships or boundaries in data. Below we will explore how to plot and customize dashed lines using Matplotlib. To plot dashed line: S
    2 min read
  • How to add a legend to a scatter plot in Matplotlib ?
    In this article, we are going to add a legend to the depicted images using matplotlib module. We will use the matplotlib.pyplot.legend() method to describe and label the elements of the graph and distinguishing different plots from the same graph.  Syntax: matplotlib.pyplot.legend( ["title_1", "Titl
    2 min read
  • How to Add Constant Line to Animated Plot in Plotly?
    Animated plots are a useful way to visualize data over time or to highlight the relationship between different variables. In this article, we will learn how to create animated plots using the plot_ly() function in R Programming Language. To create an animated plot in R, we will use the plot_ly() fun
    2 min read
  • How to use matplotlib plot inline?
    Matplotlib is a Python library that helps in drawing graphs. It is used in data visualization and graph plotting. Matplotlib Plot Inline is a package that supports Matplotlib to display plots directly inline and save them to notebooks. In this article, we'll cover the following:  What is Matplotlib
    3 min read
  • How to Plot a Smooth Curve in Matplotlib?
    Prerequisite: Introduction to Matplotlib Many times we have line plots generated from lists of data that are quite scattered which makes graphs seem like straight lines connecting dots or quite dense which leads to the data points being extremely close to each other and hence the plot looks cluttere
    4 min read
  • How to Add Title to Subplots in Matplotlib?
    In this article, we will see how to add a title to subplots in Matplotlib? Let's discuss some concepts : Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work
    3 min read
  • How to update a plot in Matplotlib?
    In this article, let's discuss how to update a plot in Matplotlib. Updating a plot simply means plotting the data, then clearing the existing plot, and then again plotting the updated data and all these steps are performed in a loop.  Functions Used:canvas.draw(): It is used to update a figure that
    2 min read
  • How to Change Line Color in Matplotlib?
    Matlab's plotting functions are included in Python by the Inclusion of the library Matplotlib. The library allows the plotting of the data of various dimensions without ambiguity in a plot. The library is widely used in Data Science and Data visualization. In this article, we will discuss how to cha
    3 min read
  • Add Text Inside the Plot in Matplotlib
    In this article, we are going to see how to add text inside the plot in Matplotlib. The matplotlib.pyplot.text() function is used to add text inside the plot. The syntax adds text at an arbitrary location of the axes. It also supports mathematical expressions. Python matplotlib.pyplot.text() Syntax
    3 min read
  • How to Plot List of X, Y Coordinates in Matplotlib?
    Prerequisites:  Matplotlib numpy  Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. To plot any data the most basic step starts with creating or loading it, this article discusses all the ways of passing the data to be plotted as list. Whi
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences