Add mean line to histogram python

I am drawing a histogram using matplotlib in python, and would like to draw a line representing the average of the dataset, overlaid on the histogram as a dotted line (or maybe some other color would do too). Any ideas on how to draw a line overlaid on the histogram?

I am using the plot() command, but not sure how to draw a vertical line (i.e. what value should I give for the y-axis?

thanks!

asked Apr 23, 2013 at 23:35

user308827user308827

18.5k77 gold badges237 silver badges388 bronze badges

You can use plot or vlines to draw a vertical line, but to draw a vertical line from the bottom to the top of the y axis, axvline is the probably the simplest function to use. Here's an example:

In [80]: import numpy as np

In [81]: import matplotlib.pyplot as plt

In [82]: np.random.seed(6789)

In [83]: x = np.random.gamma(4, 0.5, 1000)

In [84]: result = plt.hist(x, bins=20, color='c', edgecolor='k', alpha=0.65)

In [85]: plt.axvline(x.mean(), color='k', linestyle='dashed', linewidth=1)
Out[85]: 

Result:

Add mean line to histogram python

answered Apr 23, 2013 at 23:56

Warren WeckesserWarren Weckesser

105k19 gold badges176 silver badges198 bronze badges

1

This is old topic and minor addition, but one thing I have often liked is to also plot mean value beside the line:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(6789)
x = np.random.gamma(4, 0.5, 1000)
result = plt.hist(x, bins=20, color='c', edgecolor='k', alpha=0.65)
plt.axvline(x.mean(), color='k', linestyle='dashed', linewidth=1)

min_ylim, max_ylim = plt.ylim()
plt.text(x.mean()*1.1, max_ylim*0.9, 'Mean: {:.2f}'.format(x.mean()))

Which produces following result:

Add mean line to histogram python

Add mean line to histogram python

rysqui

2,6492 gold badges18 silver badges25 bronze badges

answered Oct 24, 2018 at 4:41

Add mean line to histogram python

I would look at the largest value in your data set (i.e. the histogram bin values) multiply that value by a number greater than 1 (say 1.5) and use that to define the y axis value. This way it will appear above your histogram regardless of the values within the histogram.

answered Apr 23, 2013 at 23:38

smitecsmitec

3,0291 gold badge15 silver badges12 bronze badges

1

In this tutorial, we will learn how to add mean or median vertical line to a plot made with Seaborn’s displot() function. Seaborn’s displot() offers capability to visualize the univariate or bivariate distribution of data. Here we will make a histogram with Seaborn’s displot() and then see how to add median line to the histogram,

Let us load the libraries needed.

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

Histogram with Seaborn’s displot()

We will using penguins data available from seaborn to make histogram with displot (not distplot) function.

penguins = sns.load_dataset("penguins")
sns.displot(penguins,
            x = "flipper_length_mm",
            bins=30,
            height=8)
plt.xlabel("Flipper Length", size=14)
plt.ylabel("Count", size=14)
plt.savefig("Seaborn_displot_histogram_Python.png")
Add mean line to histogram python
Histogram with Seaborn displot()

Add Mean line to Histogram with axvline()

We will use Matplotlib’s axvline() function to add mean line to the histogram made with Seaborn’s displot(). We also specify color argument to make the mean line in red color.

sns.displot(penguins,
            x = "flipper_length_mm",
            bins=30,
           height=8)
plt.xlabel("Flipper Length", size=14)
plt.ylabel("Count", size=14)
plt.axvline(x=penguins.flipper_length_mm.mean(),
            color='red')
plt.savefig("Seaborn_displot_histogram_with_mean_line_Python.png")
Add mean line to histogram python
Seaborn displot with median line

Customizing Mean line to Histogram with axvline()

To further customize the mean/median line to the histogram we use line type with “ls” and line width using “lw” to make a thicker dotted median line.

sns.displot(penguins,
            x = "flipper_length_mm",
            bins=30,
           height=8)
plt.xlabel("Flipper Length", size=14)
plt.ylabel("Count", size=14)
plt.axvline(x=penguins.flipper_length_mm.median(),
            color='blue',
            ls='--', 
            lw=2.5)
plt.savefig("Seaborn_displot_histogram_with_median_line_Python.png")
Add mean line to histogram python
Seaborn displot with median line

How do you add an average line to a histogram in Python?

Get the data for x using some equations, set num_bins = 50..
Create fig and ax variables using subplots method, where default nrows and ncols are 1..
Get n, bins, patches value using ax. ... .
Plot average lines using bins and y data that is obtained from some equations..
Set the X-axis label using plt..

How do you plot a line on a histogram?

Add a subplot to the current figure, nrows=2, ncols=1 and index=1..
Use numpy histogram method to get the histogram of a set of data..
Plot the histogram using hist() method with edgecolor=black..
At index 2, use the computed data (from numpy histogram). ... .
To display the figure, use show() method..

How do you make a vertical line in Python?

Use plt. Call plt. axvline(x) to plot a vertical line at the desired x value.

How do you add bins to a histogram in Python?

You can use one of the following methods to adjust the bin size of histograms in Matplotlib:.
Method 1: Specify Number of Bins plt. hist(data, bins=6).
Method 2: Specify Bin Boundaries plt. hist(data, bins=[0, 4, 8, 12, 16, 20]).
Method 3: Specify Bin Width w=2 plt. hist(data, bins=np. arange(min(data), max(data) + w, w)).