{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Left-aligned y tick labels\n\nBy default, tick labels are aligned towards the axis. This means the set of\ny tick labels appear right-aligned.\n\nTo obtain left-aligned y tick labels, a solution is to force their\nhorizontal-alignment to \"left\". However, because the alignment reference point\nis on the axis, such labels would overlap the plotting area, so the label\npadding needs to be additionally increased.\n\nAn alternate solution is to use the mathtext commands ``\\rlap`` and\n``\\phantom`` to manipulate the widths of the tick labels as seen by Matplotlib.\nSee https://www.tug.org/TUGboat/tb22-4/tb72perlS.pdf for a detailed description\nof this approach.\n\nSee also :doc:`/gallery/axisartist/demo_ticklabel_alignment`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\npopulation = {\n \"Sydney\": 5.2,\n \"Mexico City\": 8.8,\n \"S\u00e3o Paulo\": 12.2,\n \"Istanbul\": 15.9,\n \"Lagos\": 15.9,\n \"Shanghai\": 21.9,\n}\n\nfig, axs = plt.subplots(1, 2, layout=\"constrained\")\n\n# First solution: Force the horizontal-alignment of y tick labels to \"left\",\n# and increase the padding (to a manually chosen value).\n\nax = axs[0]\nax.barh(population.keys(), population.values())\nax.set_xlabel('Population (in millions)')\nfor ticklabel in ax.get_yticklabels():\n ticklabel.set_horizontalalignment(\"left\")\nax.tick_params(\"y\", pad=70)\n\n\n# Second solution: Use mathtext to manipulate the width of ylabels as seen\n# by Matplotlib. Here, \\rlap means \"draw this text, but don't advance the\n# cursor\", whereas \\phantom means \"advance the cursor by the width of the\n# enclosed text, but without actually drawing the text\". The end result is\n# that the labels get aligned as if \"Mexico City\" was written every time, but\n# the real labels are actually drawn.\n\n# Note that the widest label (\"Mexico City\") is still hard-coded here (it is\n# the widest *rendered* label, which is not necessarily the longest label in\n# characters).\ndef left_aligned_label(s):\n return r\"$\\rlap{\\text{%s}}\\phantom{\\text{Mexico City}}$\" % s\n\nax = axs[1]\nax.barh([*map(left_aligned_label, population)], population.values())\nax.set_xlabel('Population (in millions)')\n\nplt.show()" ] } ], "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.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }