在 y 轴上添加标签以显示 matplotlib 中水平线的 y 值 [英] Add a label to y-axis to show the value of y for a horizontal line in matplotlib

查看:41
本文介绍了在 y 轴上添加标签以显示 matplotlib 中水平线的 y 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 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")

推荐答案

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

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()

这篇关于在 y 轴上添加标签以显示 matplotlib 中水平线的 y 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆