matplotlib:我能在 `axhline` 中断并添加文本吗?

7
在绘制的图中,我想要画一条axhline,并在其值上进行注释,有点类似于轮廓图示例here。例如,看起来像这样:--------- 0.13 -----------。这在matplotlib中是否可能?
2个回答

15

您可以在线段的中心点创建一个普通的text对象,然后将背景颜色设置为与轴的颜色相同,这样水平线就不会在文本后面显示。

plt.axhline(linewidth=4, y=0.5, color='red')

plt.text(0.5, 0.5, 'text', fontsize=30, va='center', ha='center', backgroundcolor='w')

enter image description here


1
如果x轴是日期,那么在plt.text(0.5, 0.5, 'text', fontsize=30, va='center', ha='center', backgroundcolor='w')中第一个0.5应该替换成什么? - mArk
如何移除白色背景? - Rylan Schaeffer
@RylanSchaeffer 白色背景是必要的,以“覆盖”红色线条。你应该能够将其设置为与你的axes相同的颜色。 - Suever

1
如果您想在彩色图像中添加这样的水平线,则“白色背景”方法将无法奏效。相反,您可以编写一个小助手函数,该函数绘制由文本间断的两条线:

enter image description here

import matplotlib.pyplot as plt
import numpy as np

def hline_text(x, y, text, color="k", fontsize=12, linestyle="-", ax=None):
    """ draw hline at y interrupted by text at x """
    if ax is None:
        ax = plt.gca()
    text = f" {text} "  # pad with single space
    label = ax.text(x, y, text, color=color, fontsize=fontsize,
                    va="center", ha="center")
    # draw text to get its bounding box
    ax.get_figure().canvas.draw()
    bbox = label.get_window_extent().transformed(ax.transData.inverted())
    # add hlines next to bounding box
    left, right = ax.get_xlim()
    ax.hlines([y]*2, [left, bbox.x1], [bbox.x0, right], color=color, linestyle=linestyle)

# draw gradient
x = np.arange(130).reshape((10, 13))
plt.imshow(x, interpolation='bilinear')
# add text & hline to current axes
hline_text(6, 7, "hello world")
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接