{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Setting tick labels from a list of values\n\nUsing `.Axes.set_xticks` causes the tick labels to be set on the currently\nchosen ticks. However, you may want to allow matplotlib to dynamically\nchoose the number of ticks and their spacing.\n\nIn this case it may be better to determine the tick label from the\nvalue at the tick. The following example shows how to do this.\n\nNB: The `.ticker.MaxNLocator` is used here to ensure that the tick values\ntake integer values.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n\nfrom matplotlib.ticker import MaxNLocator\n\nfig, ax = plt.subplots()\nxs = range(26)\nys = range(26)\nlabels = list('abcdefghijklmnopqrstuvwxyz')\n\n\ndef format_fn(tick_val, tick_pos):\n if int(tick_val) in xs:\n return labels[int(tick_val)]\n else:\n return ''\n\n\n# A FuncFormatter is created automatically.\nax.xaxis.set_major_formatter(format_fn)\nax.xaxis.set_major_locator(MaxNLocator(integer=True))\nax.plot(xs, ys)\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.pyplot.subplots`\n - `matplotlib.axis.Axis.set_major_formatter`\n - `matplotlib.axis.Axis.set_major_locator`\n - `matplotlib.ticker.FuncFormatter`\n - `matplotlib.ticker.MaxNLocator`\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 }