{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Tick formatters\n\nTick formatters define how the numeric value associated with a tick on an axis\nis formatted as a string.\n\nThis example illustrates the usage and effect of the most common formatters.\n\nThe tick format is configured via the function `~.Axis.set_major_formatter`\nor `~.Axis.set_minor_formatter`. It accepts:\n\n- a format string, which implicitly creates a `.StrMethodFormatter`.\n- a function, implicitly creates a `.FuncFormatter`.\n- an instance of a `.Formatter` subclass. The most common are\n\n - `.NullFormatter`: No labels on the ticks.\n - `.StrMethodFormatter`: Use string `str.format` method.\n - `.FormatStrFormatter`: Use %-style formatting.\n - `.FuncFormatter`: Define labels through a function.\n - `.FixedFormatter`: Set the label strings explicitly.\n - `.ScalarFormatter`: Default formatter for scalars: auto-pick the format string.\n - `.PercentFormatter`: Format labels as a percentage.\n\n See `formatters` for a complete list.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nfrom matplotlib import ticker\n\n\ndef setup(ax, title):\n \"\"\"Set up common parameters for the Axes in the example.\"\"\"\n # only show the bottom spine\n ax.yaxis.set_major_locator(ticker.NullLocator())\n ax.spines[['left', 'right', 'top']].set_visible(False)\n\n # define tick positions\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))\n ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))\n\n ax.xaxis.set_ticks_position('bottom')\n ax.tick_params(which='major', width=1.00, length=5)\n ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)\n ax.set_xlim(0, 5)\n ax.set_ylim(0, 1)\n ax.text(0.0, 0.2, title, transform=ax.transAxes,\n fontsize=14, fontname='Monospace', color='tab:blue')\n\n\nfig = plt.figure(figsize=(8, 8), layout='constrained')\nfig0, fig1, fig2 = fig.subfigures(3, height_ratios=[1.5, 1.5, 7.5])\n\nfig0.suptitle('String Formatting', fontsize=16, x=0, ha='left')\nax0 = fig0.subplots()\n\nsetup(ax0, title=\"'{x} km'\")\nax0.xaxis.set_major_formatter('{x} km')\n\n\nfig1.suptitle('Function Formatting', fontsize=16, x=0, ha='left')\nax1 = fig1.subplots()\n\nsetup(ax1, title=\"def(x, pos): return str(x-5)\")\nax1.xaxis.set_major_formatter(lambda x, pos: str(x-5))\n\n\nfig2.suptitle('Formatter Object Formatting', fontsize=16, x=0, ha='left')\naxs2 = fig2.subplots(7, 1)\n\nsetup(axs2[0], title=\"NullFormatter()\")\naxs2[0].xaxis.set_major_formatter(ticker.NullFormatter())\n\nsetup(axs2[1], title=\"StrMethodFormatter('{x:.3f}')\")\naxs2[1].xaxis.set_major_formatter(ticker.StrMethodFormatter(\"{x:.3f}\"))\n\nsetup(axs2[2], title=\"FormatStrFormatter('#%d')\")\naxs2[2].xaxis.set_major_formatter(ticker.FormatStrFormatter(\"#%d\"))\n\n\ndef fmt_two_digits(x, pos):\n return f'[{x:.2f}]'\n\n\nsetup(axs2[3], title='FuncFormatter(\"[{:.2f}]\".format)')\naxs2[3].xaxis.set_major_formatter(ticker.FuncFormatter(fmt_two_digits))\n\nsetup(axs2[4], title=\"FixedFormatter(['A', 'B', 'C', 'D', 'E', 'F'])\")\n# FixedFormatter should only be used together with FixedLocator.\n# Otherwise, one cannot be sure where the labels will end up.\npositions = [0, 1, 2, 3, 4, 5]\nlabels = ['A', 'B', 'C', 'D', 'E', 'F']\naxs2[4].xaxis.set_major_locator(ticker.FixedLocator(positions))\naxs2[4].xaxis.set_major_formatter(ticker.FixedFormatter(labels))\n\nsetup(axs2[5], title=\"ScalarFormatter()\")\naxs2[5].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))\n\nsetup(axs2[6], title=\"PercentFormatter(xmax=5)\")\naxs2[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))\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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }