{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Align y-labels\n\nTwo methods are shown here, one using a short call to `.Figure.align_ylabels`\nand the second a manual way to align the labels.\n\n.. redirect-from:: /gallery/pyplots/align_ylabels\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef make_plot(axs):\n box = dict(facecolor='yellow', pad=5, alpha=0.2)\n\n # Fixing random state for reproducibility\n np.random.seed(19680801)\n ax1 = axs[0, 0]\n ax1.plot(2000*np.random.rand(10))\n ax1.set_title('ylabels not aligned')\n ax1.set_ylabel('misaligned 1', bbox=box)\n ax1.set_ylim(0, 2000)\n\n ax3 = axs[1, 0]\n ax3.set_ylabel('misaligned 2', bbox=box)\n ax3.plot(np.random.rand(10))\n\n ax2 = axs[0, 1]\n ax2.set_title('ylabels aligned')\n ax2.plot(2000*np.random.rand(10))\n ax2.set_ylabel('aligned 1', bbox=box)\n ax2.set_ylim(0, 2000)\n\n ax4 = axs[1, 1]\n ax4.plot(np.random.rand(10))\n ax4.set_ylabel('aligned 2', bbox=box)\n\n\n# Plot 1:\nfig, axs = plt.subplots(2, 2)\nfig.subplots_adjust(left=0.2, wspace=0.6)\nmake_plot(axs)\n\n# just align the last column of Axes:\nfig.align_ylabels(axs[:, 1])\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. seealso::\n `.Figure.align_ylabels` and `.Figure.align_labels` for a direct method\n of doing the same thing.\n Also :doc:`/gallery/subplots_axes_and_figures/align_labels_demo`\n\n\nOr we can manually align the axis labels between subplots manually using the\n`~.Axis.set_label_coords` method of the y-axis object. Note this requires\nwe know a good offset value which is hardcoded.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, axs = plt.subplots(2, 2)\nfig.subplots_adjust(left=0.2, wspace=0.6)\n\nmake_plot(axs)\n\nlabelx = -0.3 # axes coords\n\nfor j in range(2):\n axs[j, 1].yaxis.set_label_coords(labelx, 0.5)\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.figure.Figure.align_ylabels`\n - `matplotlib.axis.Axis.set_label_coords`\n - `matplotlib.axes.Axes.plot` / `matplotlib.pyplot.plot`\n - `matplotlib.axes.Axes.set_title`\n - `matplotlib.axes.Axes.set_ylabel`\n - `matplotlib.axes.Axes.set_ylim`\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }