首页 > 解决方案 > 如何处理文本框的长度以适合 Matplotlib 中的一个子图?

问题描述

我正在尝试在图形的第一个子图上添加以下文本。

txt = "NY Fed WEI is an index of ten daily and weekly indicators of real economic activity:Initial unemployment isurance claims; continuing unemployment insurance claims; federal taxes with-held; Redbook same-store sales; Rasmussen consumer index; American Staffing Assoc. Staffing Index; raw steel production; US railroad traffic; US fuel sales to end users; US electricity output"

ax.annotate(txt, xy=(0, 1), xycoords='axes fraction' ,xytext=(-5, 5), textcoords='offset points',ha='left', va='top', **{'fontsize':'x-small', 'wrap':True})

在此处输入图像描述

我希望整个文本仅在第一个子图上,即在美国 GDP 之下,并且不希望它扩展到另一个子图,即美国商业投资。我也使用了以下代码,但即使这样也给出了类似的结果。

ax.text(0, 0.7, txt, ha='left', va='top', wrap=True, fontsize=5, transform=ax.transAxes, bbox=dict(boxstyle='square', fc='w'))

有没有办法将下图中的文本放在单个子图上? 在此处输入图像描述

标签: pythonmatplotlib

解决方案


您需要使用_get_wrap_line_width来定义线宽。以下对我有用:

text = ax.text(0, 0.9, txt, ha='left', va='top', wrap=True, fontsize=5, transform=ax.transAxes)
text._get_wrap_line_width = lambda : 250.

transform=ax.transAxes将所有内容放在轴上而不是图形上很重要。


推荐阅读