我有这个例子:

from numpy import linspace, sin
from matplotlib.pyplot import plot, ylabel, gcf, text

x = linspace(0, 1)
y = x ** 2
plot(x, y)
ylabel("test")

现在,我想在此图中放置一些类似"abc"的文本approximately:

A cut out version of the plot that would be generated by the above code, showing parts of the left y-axix and the y-axis label. The text

为此,我需要y标签的x坐标,或者至少是近似值.我try 了以下几种方法:

xd, _ = pyplot.gca().yaxis.get_label().get_transform().transform((0, 0))

但现在似乎xd在显示坐标中总是0.这显然是不正确的.此外,如果我想将其转换回图形坐标来显示文本:

x, _ = gcf().transFigure.inverted().transform_point((xd, 0))
text(0, 0.5, "abcdefg", transform=gcf().transFigure)

我明白了:

A cut out version of the plot that would be generated by the above code, showing parts of the left y-axix and the y-axis label. The text

所以很明显,x坐标是不正确的.

推荐答案

将讨论合并为一个答案:

enter image description here

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_ylabel("test")
# draw the elements
fig.draw_without_rendering()
# get the position of the ylabel and transform it to coordinates
pos_pixel = ax.yaxis.label.get_tightbbox()
x_coord = ax.transData.inverted().transform((pos_pixel.x0, pos_pixel.y0))[0]
plt.text(x_coord, 0.42, "abc", color="red")
plt.show()

Python相关问答推荐

这些变量是否相等,因为它们引用相同的实例,尽管它们看起来应该具有不同的值?

单击Cookie横幅错误并在Selenium中启用搜索栏

如何使用PyTest根据self 模拟具有副作用的属性

如何将我的位置与光强度数据匹配到折射图案曲线中?

Pydantic:如何将对象列表表示为dict(将列表序列化为dict)

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

如何让程序打印新段落上的每一行?

Telethon加入私有频道

两个pandas的平均值按元素的结果串接元素.为什么?

OR—Tools中CP—SAT求解器的IntVar设置值

对象的`__call__`方法的setattr在Python中不起作用'

优化器的运行顺序影响PyTorch中的预测

Pandas DataFrame中行之间的差异

移动条情节旁边的半小提琴情节在海运

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

无法连接到Keycloat服务器

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

从Windows Python脚本在WSL上运行Linux应用程序

pandas:对多级列框架的列进行排序/重新排序

Matplotlib中的字体权重