How to set labels in matplotlib.hlines?


To set labels in matplotlib.hlines, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Add a horizontal line across the axis, y=1, with y=1 label, color='orange'.
  • Add a horizontal line across the axis, y=2, with y=2 label, color='red'.
  • To display the figure, use show() method.

Example

import matplotlib.pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Add horizontal line
plt.hlines(y=1, xmin=1, xmax=4, lw=7, color='orange')
plt.text(4, 1, 'y=1', ha='left', va='center')

# Add another horizontal line
plt.hlines(y=2, xmin=2, xmax=5, lw=7, color='red')
plt.text(2, 2, 'y=2', ha='right', va='center')

plt.show()

Output

It will produce the following output

Updated on: 19-Sep-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements