Matplotlib - 合并文本/注释坐标系统

6 投票
1 回答
889 浏览
提问于 2025-06-18 04:11

有没有办法在图表上定位文本或注释时,结合两种不同的坐标系统呢?在这个问题中提到,你可以把注释的位置指定为图表大小的一个分数位置。这个内容在文档的这里也有进一步的说明。

不过我想把注释的x坐标用分数坐标系统来表示,而y坐标则用数据坐标系统来表示。这样做可以让我把注释固定在一条水平线上,同时确保注释总是离图表的边缘有一定的距离(也就是图表大小的一部分)。

相关问题:

  • 暂无相关问题
暂无标签

1 个回答

5

使用 blended_transform_factory(x_transform,y_transform)。这个函数会返回一个新的变换,它会对x轴应用 x_transform,对y轴应用 y_transform。举个例子:

import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory
import numpy as np

x = np.linspace(0, 100,1000)
y = 100*np.sin(x)
text = 'Annotation'

f, ax = plt.subplots()
ax.plot(x,y)
trans = blended_transform_factory(x_transform=ax.transAxes, y_transform=ax.transData)
ax.annotate(text, xy=[0.5, 50], xycoords=trans,ha='center')

这样你就可以把注释放在x轴的中间,以及y轴上y=50的位置。

enter image description here

撰写回答