繁体   English   中英

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

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

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

plt.plot((0,502),(305,305),'r-')
plt.title("ALS+REG")

情节

可以使用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()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM