可以反复更改字体大小,直到标题宽度小于轴。我想不让标题小于1pt是有意义的(即使它不再可读,所以请随意选择一个不同的数字)。下面以1pt的fontsize步骤迭代;也可以对此进行调整。
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot([1,2])
ax1.set_title("Short title")
ax2.plot([2,1])
ax2.set_title("Loooooong title, which exceeds plot axes width.")
def adjust_title(ax):
title = ax.title
ax.figure.canvas.draw()
def _get_t():
ax_width = ax.get_window_extent().width
ti_width = title.get_window_extent().width
return ax_width/ti_width
while _get_t() <= 1 and title.get_fontsize() > 1:
title.set_fontsize(title.get_fontsize()-1)
adjust_title(ax1)
adjust_title(ax2)
plt.show()