注意
转到末尾 以下载完整的示例代码。
自动换行#
Matplotlib 可以自动换行,但如果文本太长,文本仍会稍微超出坐标轴的边界显示。
注意:自动换行不兼容 savefig(..., bbox_inches='tight')
。‘tight’(紧密)设置会重新缩放画布以适应所有内容,且此操作发生在换行之前。这会影响 IPython 和 Jupyter notebook 中的 %matplotlib inline
,其中 inline 设置在保存嵌入图像时默认使用 bbox_inches='tight')
。

import matplotlib.pyplot as plt
fig = plt.figure()
plt.axis((0, 10, 0, 10))
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!")
plt.text(4, 1, t, ha='left', rotation=15, wrap=True)
plt.text(6, 5, t, ha='left', rotation=15, wrap=True)
plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)
plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',
va='top', wrap=True)
plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)
plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)
plt.show()
脚本总运行时间:(0 分钟 1.397 秒)