{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Multiline text\n\nTexts may contain newlines to create multiline text.\n\nThe text alignment of the individual lines can be controlled by the\n``multialignment`` parameter. If not set, the alignment of the lines is inferred from\nthe ``horizontalalignment`` and ``verticalalignment`` parameters, which primarily\ncontrol the alignment of the bounding box of the text to its anchor point; e.g. if the\ntext has the anchor point to its right, all text lines will be aligned to the right\nso that they pick up that anchor point.\n\nWhen using mutli-line labels, it is recommended to use a layout manager (e.g.\n``layout=\"constrained\"``) to ensure that there is enough space for the labels..\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(layout=\"constrained\")\n\nax.bar(range(6), [0.3, 0.5, 0.8, 1.5, 2.5, 8], alpha=0.3)\n\nax.set_ylabel('labels are centered,\\nso is their multi-line text by default')\nax.set_xlabel('xlabel with\\nmultialignment=\"left\"', multialignment=\"left\")\n\nax.text(\n 4.5, 6,\n 'these lines\\n'\n 'are right aligned\\n'\n 'because of horizontalalignment',\n horizontalalignment='right',\n)\n\nax.text(\n 4.5, 4,\n 'but\\n'\n 'we can override this\\n'\n 'with an explicit multialingment=\"left\"',\n horizontalalignment='right',\n multialignment='left',\n)\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each line has the same height irrespective of the used characters unless\nthere is math text involved, which may need more vertical space\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n\nax.text(0.1, 0.4, \"Mat\\nTTp\\n123\", size=18,\n va=\"baseline\", bbox=dict(fc=\"none\", ec=\"tab:orange\"))\n\nax.text(0.3, 0.4, \"Mag\\nTTT\\n123\", size=18,\n va=\"baseline\", bbox=dict(fc=\"none\", ec=\"tab:orange\"))\n\nax.text(0.5, 0.4, \"Mag\\nTTT$^{A^A}$\\n123\", size=18,\n va=\"baseline\", bbox=dict(fc=\"none\", ec=\"tab:orange\"))\n\nax.axhline(0.4)\nax.set_title(\"test line spacing for multiline text\")\nax.set_xlim(0, 0.7)\nax.yaxis.minorticks_on()\nax.yaxis.set_tick_params(which=\"minor\", grid_color=\"0.9\")\nax.grid(which=\"both\")\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 }