Add a label to y-axis to show the value of y for a horizontal line in matplotlib

前端 未结 1 2130
情话喂你
情话喂你 2021-02-10 22:13

How can I add a string label to the horizontal red line showed in the following plot? I want to add something like \"k=305\" to the y-axis label next to the line. The blue dots

相关标签:
1条回答
  • 2021-02-10 22:48

    A horizontal line can be drawn using Axes.axhline(y).
    Adding a label would be done by using Axes.text(). THe tricky bit is to decide upon the coordinates at which to place that text. Since the y coordinate should be the data coordinate at which the line is drawn, but the x coordinate of the label should be the independent of the data (e.g. allow for differen axis scales), we can use a blended transform, where the x transform is the transform of the axis ylabels, and the y transform is the data coordinate system.

    import matplotlib.pyplot as plt
    import matplotlib.transforms as transforms
    import numpy as np; np.random.seed(42)
    
    N = 120
    x = np.random.rand(N)
    y = np.abs(np.random.normal(size=N))*1000
    mean= np.mean(y)
    
    fig, ax=plt.subplots()
    ax.plot(x,y, ls="", marker="o", markersize=2)
    ax.axhline(y=mean, color="red")
    
    trans = transforms.blended_transform_factory(
        ax.get_yticklabels()[0].get_transform(), ax.transData)
    ax.text(0,mean, "{:.0f}".format(mean), color="red", transform=trans, 
            ha="right", va="center")
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题