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
Adding a Horizontal Line in Python Plot (1)
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5, linewidth=3.0)
#Horizontal Line at y=-5 with linewidth=3.0
Adding a Horizontal Line in Python Plot (2)
plt.plot(x,y, '.-', color='purple')
plt.axhline(y=-5, color='grey')
#Horizontal Line at y=-5 with grey color
Adding a Horizontal Line in Python Plot (3)
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
Adding a Horizontal Line in Python Plot (4)

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.