Plot horizontal lines in Matplotlib

Python

Matplotlib

Line

Plot horizontal

Luc B.

Python

Matplotlib

Line Plot

Horizontal lines are useful for highlighting specific moments in a plot. While horizontal lines can easilly be plotted with plt.plot(), Matplotlib provides a convenience function, plt.hlines(), to make plotting horizontal lines easier and more readable.

Code Example

Use the plt.hlines() function to create horizontal lines in Matplotlib. plt.hlines() takes three parameters, an array of y-values specifying where to plot the lines followed by the x-values the line should span. If you only want to plot one horizontal line, pass a number as the first parameter instead of an array.

import matplotlib.pyplot as plt

# Create horizontal lines here
plt.hlines([2, 3, 4, 5], 0, 1)

plt.show()

png