vertical & horizontal lines in matplotlib

后端 未结 3 1377
有刺的猬
有刺的猬 2020-11-29 21:27

I do not quite understand why I am unable to create horizontal and vertical lines at specified limits. I would like to bound the data by this box. However, the sides do not

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 21:49

    This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

    The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

    On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

    Let's take a concrete example,

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 5, 100)
    y = np.sin(x)
    
    fig, ax = plt.subplots()
    
    ax.plot(x, y)
    ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
    ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')
    
    plt.show()
    

    It will produce the following plot:

    The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

提交回复
热议问题