How to Add an Average Line to Plot in Matplotlib
Last Updated : 24 Apr, 2025
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:
outputNow, 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
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
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
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
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:
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.
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