How do i add a vertical line to a histogram in 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.8k74 gold badges236 silver badges386 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:

How do i add a vertical line to a histogram in python?

answered Apr 23, 2013 at 23:56

Warren WeckesserWarren Weckesser

105k19 gold badges176 silver badges197 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:

How do i add a vertical line to a histogram in python?

How do i add a vertical line to a histogram in python?

rysqui

2,6492 gold badges18 silver badges25 bronze badges

answered Oct 24, 2018 at 4:41

How do i add a vertical line to a histogram in 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

Not the answer you're looking for? Browse other questions tagged python matplotlib axis or ask your own question.

Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots. Plotting a horizontal line is fairly simple, The following code shows how it can be done.

Making a single vertical line

Method #1: Using axvline()

This function adds the vertical lines across the axes of the plot

Syntax: matplotlib.pyplot.axvline(x, color, xmin, xmax, linestyle)

Parameters:

  • x: Position on X axis to plot  the line, It accepts integers.
  • xmin and xmax: scalar, optional, default: 0/1.  It plots the line in the given range
  • color: color for the line, It accepts  a string. eg ‘r’ or ‘b’ .
  • linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’

Python3

import matplotlib.pyplot as plt

import numpy as np

plt.figure(figsize = (10, 5))

plt.axvline(x = 7, color = 'b', label = 'axvline - full height')

plt.show()

Output:

How do i add a vertical line to a histogram in python?

Method #2: Using vlines()

matplotlib.pyplot.vlines() is a function used in the plotting of a dataset. In matplotlib.pyplot.vlines(), vlines is the abbreviation for vertical lines. What this function does is very much clear from the expanded form, which says that function deals with the plotting of the vertical lines across the axes.

Syntax: vlines(x, ymin, ymax, colors, linestyles)

Parameters:

  • x: Position on X axis to plot  the line, It accepts integers.
  • xmin and xmax: scalar, optional, default: 0/1.  It plots the line in the given range
  • color: color for the line, It accepts  a string. eg ‘r’ or ‘b’ .
  • linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’

Python3

import matplotlib.pyplot as plt

import numpy as np

xs = [1, 100]

plt.figure(figsize = (10, 7))

plt.vlines(x = 37, ymin = 0, ymax = max(xs),

           colors = 'purple',

           label = 'vline_multiple - full height')

plt.show()

 
 Output:

How do i add a vertical line to a histogram in python?

Method #3: Using plot() 

The plot() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y.

Syntax : plot(x_points, y_points, scaley = False)

Parameters:

  • x_points/y_points: points to plot
  • scalex/scaley: Bool, These parameters determine if the view limits are adapted to the data limits

Python3

import matplotlib.pyplot as plt

plt.figure(figsize = (10, 5))

plt.plot((0, 0), (0, 1), scaley = False)

plt.show()

 
 Output:

How do i add a vertical line to a histogram in python?

Plotting multiple lines with the legend

The below methods can be used for plotting multiple lines in Python.

Method #1: Using axvline() 

Python3

import matplotlib.pyplot as plt

import numpy as np

plt.figure(figsize = (10, 5))

plt.axvline(x = 7, color = 'b', label = 'axvline - full height')

plt.axvline(x = 7.25, ymin = 0.1, ymax = 0.90, color = 'r',

            label = 'axvline - % of full height')

plt.legend(bbox_to_anchor = (1.0, 1), loc = 'upper left')

plt.show()

Output:

How do i add a vertical line to a histogram in python?

Method #2: Using vlines()

Python3

import matplotlib.pyplot as plt

import numpy as np

xs = [1, 100]

plt.figure(figsize = (10, 7))

plt.vlines(x = [37, 37.25, 37.5], ymin = 0, ymax = max(xs),

           colors = 'purple',

           label = 'vline_multiple - full height')

plt.vlines(x = [38, 38.25, 38.5], ymin = [0, 25, 75], ymax = max(xs),

           colors = 'teal',

           label = 'vline_multiple - partial height')

plt.vlines(x = 39, ymin = 0, ymax = max(xs), colors = 'green',

           label = 'vline_single - full height')

plt.vlines(x = 39.25, ymin = 25, ymax = max(xs), colors = 'green',

           label = 'vline_single - partial height')

plt.legend(bbox_to_anchor = (1.0, 1), loc = 'up')

plt.show()

Output:

How do i add a vertical line to a histogram in python?


How do I plot a vertical line in Matplotlib?

Making a single vertical line.
x: Position on X axis to plot the line, It accepts integers..
xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range..
color: color for the line, It accepts a string. eg 'r' or 'b' ..
linestyle: Specifies the type of line, It accepts a string. eg '-', '–', '-..

How do you plot a vertical line in pandas?

Using panda we can create a data frame..
Creating a data frame would help to create help..
Using axvline(), add a vertical line across the axes, where color is green, linestyle="dashed"..
Using axvline(), add a vertical line across the axes, where color is red, linestyle="dashed"..
Using plt. show(), show the plot..

How do you add a border to a histogram in Python?

In this example, we will Pass an edgecolor = 'Black' value as the edge color parameter to plt. hist() to change the bar border color..
Import required module..
Create data..
Add border around histogram bars..
Normally plot the data..
Display plot..

How do you insert a vertical line in Seaborn?

Seaborn's refline() function to add horizontal/vertical lines in subplots. To add a horizontal and vertical line we can use Seaborn's refline() function with x and y y co-ordinates for the locations of the horizontal and vertical lines.