.. _sphx_glr_gallery_pyplots_auto_subplots_adjust.py: ==================== Auto Subplots Adjust ==================== .. image:: /gallery/pyplots/images/sphx_glr_auto_subplots_adjust_001.png :align: center .. code-block:: python import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms fig = 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 False fig.canvas.mpl_connect('draw_event', on_draw) plt.show() **Total running time of the script:** ( 0 minutes 0.020 seconds) .. only :: html .. container:: sphx-glr-footer .. container:: sphx-glr-download :download:`Download Python source code: auto_subplots_adjust.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: auto_subplots_adjust.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_