【问题标题】:Creating labels where line appears in matplotlib figure创建线出现在matplotlib图中的标签
【发布时间】:2012-11-04 23:21:19
【问题描述】:

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

matplotlib.pyplot.axvline

行。我想在靠近这些垂直线的图上创建标签(可能在线的 RHS 和图的顶部)。

【问题讨论】:

标签: python matplotlib labels


【解决方案1】:

无需手动放置的解决方案是使用“混合转换”。

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 = ax.get_xaxis_transform()

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

plt.show()

【讨论】:

    【解决方案2】:

    你可以使用类似的东西

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

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

    【讨论】:

    • 如果要将数据坐标用于 x 轴,将轴坐标用于 y 轴,可以使用以下命令将文本放置在 x=10.1 和高度的 50% 处:ax.text(10.1, 0.5, 'blah', rotation=90, transform=ax.get_xaxis_text1_transform(0)[0])
    • 链接已过时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多