创建matplotlib图中出现线条的标签

时间:2012-11-16 08:43:51

标签: python matplotlib labels

我有一个在matplotlib(时间序列数据)中创建的图形,其中有一系列

matplotlib.pyplot.axvline

行。我想在图上创建标签,这些标签看起来很接近(可能在线的RHS和图的顶部)这些垂直线。

2 个答案:

答案 0 :(得分:49)

您可以使用类似

的内容
plt.axvline(10)
plt.text(10.1,0,'blah',rotation=90)

您可能需要使用text中的x和y值来使其正确对齐。 您可以找到更完整的文档here

答案 1 :(得分:2)

没有手动放置的解决方案是使用“混合变换”。

Transformations将坐标从一个坐标系转换到另一个坐标系。通过使用texttransform参数指定转换,可以在轴坐标系中给出文本的xy坐标(从0到1分别从x / y轴的左到右/上到下)。使用blended transformations,您可以使用混合坐标系。

这正是您所需要的:您拥有数据给出的x坐标,并且想要将文本放置在y轴上相对于该轴的某个位置,例如居中。执行此操作的代码如下:

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

fig, ax = plt.subplots()

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

x = 10
ax.axvline(x)
plt.text(x, .5, 'hello', transform=trans)

plt.show()