Home »
Python »
Python Data Visualization
Adding a Horizontal Line in Python Plot
Here, we are going to learn how to add a Horizontal Line in Python Plot?
Submitted by Anuj Singh, on July 22, 2020
In this article, we are going to learn how to add a horizontal line in matplotlib figures? A horizontal line is required for marking the extreme range or something related to saturation. In some cases, it is also used for defining outliers, and therefore, it turns out to be a good technique in data visualization, and therefore, matplotlib has an inbuilt defined function for our operation, matplotlib.pyplot.axhline().
The following example illustrates all the four possible examples.
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5)
#Horizontal Line at y=-5
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5, linewidth=3.0)
#Horizontal Line at y=-5 with linewidth=3.0
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5, color='grey')
#Horizontal Line at y=-5 with grey color
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=2, color='grey')
plt.axhline(y=-5.5, color='grey')
#Horizontal Lines at y=2 and y=-5.5, with color grey
Python code for adding a horizontal line in python plot
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0.1, 5, 0.1)
y = np.tan(x)*np.exp(-x)
plt.figure()
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5)
plt.title('Horizontal Line')
plt.show()
plt.figure()
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5, linewidth=3.0)
plt.title('Horizontal Line')
plt.show()
plt.figure()
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5, linewidth=2.0, color='grey')
plt.title('Horizontal Line')
plt.show()
plt.figure()
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=2, color='grey')
plt.axhline(y=-5.5, color='grey')
plt.title('Horizontal Line')
plt.show()
Output:
Output is as figure