我正在尝试生成一个有四个季度的情节,每个都有一些文字说明该季度。但是,当我试图包装文本时,我不知道如何设置文本的限制。例如,在附图中,我想将文本限制为 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')
答案 0 :(得分:1)
从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)