Matplotlib - Draw horizontal lines

By xngo on July 23, 2020

Matplotlib does provide hlines() function to conveniently draw horizontal lines. Here are some examples.

#!/usr/bin/python3
import matplotlib
matplotlib.use('Agg') # Bypass the need to install Tkinter GUI framework
import matplotlib.pyplot as plt
 
# Draw a simple red line at y=0.5.
plt.axhline(y=0.5, color='r', linestyle='-')
 
 
# Draw a line at y=0.2 between x-axis 0.25 and 0.8.
green_fluorescent='#83f52c'
plt.axhline(y=0.2, xmin=0.25, xmax=0.8, color=green_fluorescent, linestyle='--', linewidth=2)
 
# Save graph to file.
plt.savefig('horizontal-lines.png')

Output

Horizontal lines - examples

Github

  • https://github.com/xuanngo2001/python-examples/blob/master/matplotlib/line/horizontal-lines.py

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.