Plot a horizontal line using matplotlib

后端 未结 7 1367
旧时难觅i
旧时难觅i 2020-11-27 11:39

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. An

7条回答
  •  心在旅途
    2020-11-27 12:06

    If you want to draw a horizontal line in the axes, you might also try ax.hlines() method. You need to specify y position and xmin and xmax in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(1, 21, 200)
    y = np.exp(-x)
    
    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')
    
    plt.show()
    

    The snippet above will plot a horizontal line in the axes at y=0.2. The horizontal line starts at x=4 and ends at x=20. The generated image is:

提交回复
热议问题