自动调整子图

自动调整子图参数。 此示例显示了一种使用draw_event上的回调从ticklabels范围确定subplot参数的方法。

请注意,使用tight_layoutconstrained_layout 可以实现类似的结果; 此示例显示了如何自定义子图参数调整。

  1. import matplotlib.pyplot as plt
  2. import matplotlib.transforms as mtransforms
  3. fig, ax = plt.subplots()
  4. ax.plot(range(10))
  5. ax.set_yticks((2,5,7))
  6. labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))
  7. def on_draw(event):
  8. bboxes = []
  9. for label in labels:
  10. bbox = label.get_window_extent()
  11. # the figure transform goes from relative coords->pixels and we
  12. # want the inverse of that
  13. bboxi = bbox.inverse_transformed(fig.transFigure)
  14. bboxes.append(bboxi)
  15. # this is the bbox that bounds all the bboxes, again in relative
  16. # figure coords
  17. bbox = mtransforms.Bbox.union(bboxes)
  18. if fig.subplotpars.left < bbox.width:
  19. # we need to move it over
  20. fig.subplots_adjust(left=1.1*bbox.width) # pad a little
  21. fig.canvas.draw()
  22. return False
  23. fig.canvas.mpl_connect('draw_event', on_draw)
  24. plt.show()

自动调整子图

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. matplotlib.artist.Artist.get_window_extent
  3. matplotlib.transforms.Bbox
  4. matplotlib.transforms.Bbox.inverse_transformed
  5. matplotlib.transforms.Bbox.union
  6. matplotlib.figure.Figure.subplots_adjust
  7. matplotlib.figure.SubplotParams
  8. matplotlib.backend_bases.FigureCanvasBase.mpl_connect

下载这个示例