Plot a horizontal line using matplotlib

Ibe picture Ibe · Oct 28, 2015 · Viewed 255.3k times · Source

I have used spline interpolation to smooth a time series and would also like to add a horizontal line to the plot. But there seems to be an issue that is out of my grips. Any assistance would be really helpful. Here is what I have:

annual = np.arange(1,21,1)
l = np.array(value_list) # a list with 20 values
spl = UnivariateSpline(annual,l)
xs = np.linspace(1,21,200)
plt.plot(xs,spl(xs),'b')

plt.plot([0,len(xs)],[40,40],'r--',lw=2)
pylab.ylim([0,200])
plt.show()

problem seems to be with my use of [0,len(xs)] for horizontal line plotting.

Answer

BlivetWidget picture BlivetWidget · Oct 28, 2015

You're looking for axhline (a horizontal axis line). For example, the following will give you a horizontal line at y = 0.5:

import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()

sample figure