简体   繁体   English

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

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

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. 我想在该行旁边的y轴标签上添加类似“ k = 305”的内容。 The blue dots are just some other data and the values do not matter. 蓝点只是其他一些数据,其值无关紧要。 For recreation of this problem, you can plot any kind of data. 为了解决这个问题,您可以绘制任何类型的数据。 My question is about the red line. 我的问题是关于红线。

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

情节

A horizontal line can be drawn using Axes.axhline(y) . 可以使用Axes.axhline(y)绘制一条水平线。
Adding a label would be done by using Axes.text() . 添加标签将通过使用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 (eg 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. 由于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