在y轴上添加标签以显示matplotlib中水平线的y值

Him*_*nAB 2 python plot matplotlib

如何在下图中显示的水平红线上添加字符串标签?我想在该行旁边的y轴标签上添加类似“ k = 305”的内容。蓝点只是其他一些数据,其值无关紧要。为了解决这个问题,您可以绘制任何类型的数据。我的问题是关于红线。

plt.plot((0,502),(305,305),'r-')
plt.title("ALS+REG")
Run Code Online (Sandbox Code Playgroud)

情节

Imp*_*est 6

可以使用绘制水平线Axes.axhline(y)
使用可以添加标签Axes.text()。棘手的一点是要确定放置该文本的坐标。由于y坐标应该是绘制线条的数据坐标,但是标签的x坐标应该独立于数据(例如,允许不同的轴比例),因此我们可以使用混合变换,其中x变换是轴ylabel的变换,而y变换是数据坐标系。

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明