Plot a Horizontal line in Matplotlib
Matplotlib is a popular python library used for plotting, It provides an object-oriented API to render GUI plots
Plotting a horizontal line is fairly simple, Using axhline()
The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis.
Syntax: matplotlib.pyplot.axhline(y, color, xmin, xmax, linestyle)
Parameters:
- y: Position on Y axis to plot the line, It accepts integers.
- xmin and xmax: scalar, optional, default: 0/1. It plots the line in the given range
- color: color for the line, It accepts a string. eg ‘r’ or ‘b’ .
- linestyle: Specifies the type of line, It accepts a string. eg ‘-‘, ‘–‘, ‘-.’, ‘:’, ‘None’, ‘ ‘, ”, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’
Plotting a single horizontal line
Python3
import matplotlib.pyplot as plt
plt.axhline(y = 0.5 , color = 'r' , linestyle = '-' )
plt.show()
|
Output:
Plotting multiple horizontal lines
To plot multiple horizontal lines, use the axhline() method multiple times.
Python
import matplotlib.pyplot as plt
plt.axhline(y = . 5 , xmin = 0.25 , xmax = 0.9 )
plt.axhline(y = 3 , color = 'b' , linestyle = ':' )
plt.axhline(y = 1 , color = 'w' , linestyle = '--' )
plt.axhline(y = 2 , color = 'r' , linestyle = 'dashed' )
plt.xlabel( 'x - axis' )
plt.ylabel( 'y - axis' )
plt.show()
|
Output:
Adding the legend
The legend can be added using the legend() function.
Python3
import matplotlib.pyplot as plt
plt.axhline(y = . 5 , xmin = 0.25 , xmax = 0.9 )
plt.axhline(y = 3 , color = 'b' , linestyle = ':' , label = "blue line" )
plt.axhline(y = 1 , color = 'w' , linestyle = '--' , label = "white line" )
plt.axhline(y = 2 , color = 'r' , linestyle = 'dashed' , label = "red line" )
plt.xlabel( 'x - axis' )
plt.ylabel( 'y - axis' )
plt.legend(bbox_to_anchor = ( 1.0 , 1 ), loc = 'upper center' )
plt.show()
|
Output:
Last Updated :
12 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...