使用 x 的数据坐标、y 的轴坐标进行文本注释

ore*_*isf 17 python matplotlib plot-annotations

从文档中:

默认转换指定文本位于数据坐标中,或者,您可以指定轴坐标中的文本(0,0 为左下角,1,1 为右上角)。下面的示例将文本放置在轴的中心:

>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
...      verticalalignment='center', transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)

我可以同时 使用数据坐标吗?分别对于x和y。

示例代码:

>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
...      verticalalignment='center', transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)

潜在结果:
情节.png 情节.png

另请参阅: 将文本放在 matplotlib 图的左上角

tmd*_*son 19

这称为“混合转型”

您可以创建一个混合转换,该转换使用 x 轴的数据坐标和 y 轴的轴坐标,如下所示:

import matplotlib.transforms as transforms
trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)
Run Code Online (Sandbox Code Playgroud)

在你的最小例子中:

import random
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

fig, ax = plt.subplots()

values = [random.randint(2,30) for _ in range(15)]
ax.violinplot(values, positions=[1])

# the x coords of this transformation are data, and the
# y coord are axes
trans = transforms.blended_transform_factory(
    ax.transData, ax.transAxes)

ax.text(1, 0.9, "Text", transform=trans)

plt.savefig("plot.png")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

另外值得注意的是matplotlib 教程中的这一点,这使得在这种特殊情况下变得更容易一些:

笔记:

x 在数据坐标中、y 在轴坐标中的混合变换非常有用,我们有辅助方法来返回 mpl 在内部用于绘制刻度、刻度标签等的版本。这些方法是matplotlib.axes.Axes.get_xaxis_transform()matplotlib.axes.Axes.get_yaxis_transform()。因此,在上面的示例中,对的调用blended_transform_factory()可以替换为get_xaxis_transform

trans = ax.get_xaxis_transform()
Run Code Online (Sandbox Code Playgroud)