How to add a grid line at a specific location in matplotlib plot?

前端 未结 3 1798
感情败类
感情败类 2020-12-02 13:26

How do I add grid at a specific location on the y axis in a matplotlib plot?

3条回答
  •  不知归路
    2020-12-02 13:48

    To improve the answer of @tacaswell here's an example using the concept of axhline and tweaking it to look similar to a line grid. In this exapmle it's used a starting default grid only on the x-axis, but it's possible to add a grid also on the y-axis (or only on this axis) by simpy add ax.xaxis.grid(True) to the code.

    First one simply start drawing a line at the desired position:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.xaxis.grid(True)
    ynew = 0.3
    ax.axhline(ynew)
    
    plt.show()
    

    obtaining the following result

    that is not very similar to a line grid.
    By changing color and line width like below:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.xaxis.grid(True)
    ynew = 0.3
    ax.axhline(ynew, color='gray', linewidth=0.5)
    
    plt.show()
    

    we obtain this, that now is in practice equal to a line grid.

    If then we want also to add a tick and related label on the y-axis, in the position where the new line is:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    ax.xaxis.grid(True)
    ynew = 0.3
    ax.axhline(ynew, color='gray', linewidth=0.5)
    
    yt = ax.get_yticks()
    yt=np.append(yt,ynew)
    
    ax.set_yticks(yt)
    ax.set_yticklabels(yt)
    
    plt.show()
    

    that leads to:

    Oh no! Some approximation occurred and the label at 0.6 not represents exactly the number 0.6. Don't worry, we can fix that simply by rounding the label array like follow:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    ax.xaxis.grid(True)
    ynew = 0.3
    ax.axhline(ynew, color='gray', linewidth=0.5)
    
    yt = ax.get_yticks()
    yt=np.append(yt,ynew)
    
    ax.set_yticks(yt)
    ax.set_yticklabels(np.round(yt,1))
    
    plt.show()
    

    and TA-DAAA :)

提交回复
热议问题