如何将字符串标签添加到下图中显示的水平红线?我想将“k=305”之类的内容添加到该行旁边的 y 轴标签中。蓝点只是一些其他数据,其值并不重要。为了重现这个问题,您可以绘制任何类型的数据。我的问题是关于红线的。
plt.plot((0,502),(305,305),'r-')
plt.title("ALS+REG")
可以使用以下命令绘制水平线Axes.axhline(y)
.
添加标签可以通过使用来完成Axes.text()
。棘手的一点是决定放置该文本的坐标。由于 y 坐标应该是绘制线条的数据坐标,但标签的 x 坐标应该独立于数据(例如,允许不同的轴比例),因此我们可以使用混合变换,其中 x 变换是轴ylabels的变换,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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)