Matplotlib - 设置文本环绕的限制

Matplotlib - Set the limits for text wrapping

我正在尝试生成一个包含四个季度的情节,每个季度都有一些文字说明该季度。但是,当我尝试将文本换行时,我不知道如何设置文本限制。比如附图中,我想限制文字为x=0。但是,它会一直持续到 x 轴限制结束。请找到随附的代码和代码生成的相应图。

import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt

import numpy as np
from textwrap import wrap

font = {'size': 22}
matplotlib.rc('font', **font)
fig = plt.figure(figsize=(8, 8))
plt.axis([-10, 10, -10, 10])

ax = plt.gca()

ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.xlabel('Energy ($kWh$)')
ax.xaxis.set_label_coords(0.85, .48)
ax.xaxis.set_ticks_position('bottom')
ax.set_xlim(-10, 10)
ax.xaxis.set_ticks([])

plt.ylabel('Discomfort ($\%$)', rotation=0)
ax.yaxis.set_label_coords(0.7, 0.01)
ax.yaxis.set_ticks_position('left')
ax.set_ylim(-10, 10)
ax.yaxis.set_ticks([])

ax.annotate(
    'Reference Point', xy=(0, 0), xycoords='data',
    xytext=(-10, 2), textcoords='data', wrap=True,
    arrowprops=dict(facecolor='black'))

t = "This is a really long string that I'd rather have wrapped so that 
it doesn't go outside of the figure, but if it's long enough it will go 
off the top or bottom!"

ax.text(-10, 3.5, t, ha='left', wrap=True, fontsize=20)
plt.tight_layout()
plt.savefig('sample.png')

正如在 auto wrap demo 中所见,换行发生在图形限制处。虽然这不是很舒服,但我可以想象很多情况,这根本没有帮助,在这里,它允许通过选择正确的对齐方式来换行文本。

ax.text(0.49, 0.98, t, ha='right',va="top", wrap=True, 
        fontsize=20, transform=ax.transAxes)
ax.text(0.51, 0.98, t, ha='left',va="top", wrap=True, 
        fontsize=20, transform=ax.transAxes)
ax.text(0.49, 0.49, t, ha='right',va="top", wrap=True, 
        fontsize=20, transform=ax.transAxes)