注意
前往結尾以下載完整範例程式碼。
自動換行文字#
Matplotlib 可以自動換行文字,但如果文字太長,文字仍會稍微顯示在軸的邊界之外。
注意:自動換行無法與 savefig(..., bbox_inches='tight')
一起使用。「tight」設定會重新調整畫布大小,以容納所有內容,並在換行之前發生。這會影響 IPython 和 Jupyter Notebook 中的 %matplotlib 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 分鐘 2.055 秒)