How to plot a horizontal line using matplotlib in Python?

Sometimes, we want to plot a horizontal line using matplotlib in Python.

In this article, we’ll look at how to plot a horizontal line using matplotlib in Python.

How to plot a horizontal line using matplotlib in Python?

To plot a horizontal line using matplotlib in Python, we can use the axhline method.

For instance, we write

import matplotlib.pyplot as plt

plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()

to call axhline with the y value for the horizontal line.

And we set the color and linestyle for the line.

Then we call show to show the line.

The line y = 0.5 is then plotted.

Conclusion

To plot a horizontal line using matplotlib in Python, we can use the axhline method.