我觉得这很棘手,但是MatPlotLib常见问题解答上有一些有关此方面的信息。这很麻烦,并且需要找出各个元素(刻度标签)占用的空间…
更新: 该页面指出该
tight_layout()功能是最简单的方法,它会尝试自动更正间距。
否则,它显示了获取各种元素(例如标签)大小的方法,因此您可以更正轴元素的间距/位置。这是上述FAQ页面中的示例,该示例确定非常宽的y轴标签的宽度,并相应地调整轴宽度:
import matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsfig = plt.figure()ax = fig.add_subplot(111)ax.plot(range(10))ax.set_yticks((2,5,7))labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))def on_draw(event): bboxes = [] for label in labels: bbox = label.get_window_extent() # the figure transform goes from relative coords->pixels and we # want the inverse of that bboxi = bbox.inverse_transformed(fig.transFigure) bboxes.append(bboxi) # this is the bbox that bounds all the bboxes, again in relative # figure coords bbox = mtransforms.Bbox.union(bboxes) if fig.subplotpars.left < bbox.width: # we need to move it over fig.subplots_adjust(left=1.1*bbox.width) # pad a little fig.canvas.draw() return Falsefig.canvas.mpl_connect('draw_event', on_draw)plt.show()


