.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/ticks/tick_labels_from_values.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. meta:: :keywords: codex .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_ticks_tick_labels_from_values.py: ========================================= Setting tick labels from a list of values ========================================= Using `.Axes.set_xticks` causes the tick labels to be set on the currently chosen ticks. However, you may want to allow matplotlib to dynamically choose the number of ticks and their spacing. In this case it may be better to determine the tick label from the value at the tick. The following example shows how to do this. NB: The `.ticker.MaxNLocator` is used here to ensure that the tick values take integer values. .. GENERATED FROM PYTHON SOURCE LINES 17-42 .. code-block:: Python import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator fig, ax = plt.subplots() xs = range(26) ys = range(26) labels = list('abcdefghijklmnopqrstuvwxyz') def format_fn(tick_val, tick_pos): if int(tick_val) in xs: return labels[int(tick_val)] else: return '' # A FuncFormatter is created automatically. ax.xaxis.set_major_formatter(format_fn) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.plot(xs, ys) plt.show() .. image-sg:: /gallery/ticks/images/sphx_glr_tick_labels_from_values_001.png :alt: tick labels from values :srcset: /gallery/ticks/images/sphx_glr_tick_labels_from_values_001.png, /gallery/ticks/images/sphx_glr_tick_labels_from_values_001_2_00x.png 2.00x :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 43-53 .. admonition:: References The use of the following functions, methods, classes and modules is shown in this example: - `matplotlib.pyplot.subplots` - `matplotlib.axis.Axis.set_major_formatter` - `matplotlib.axis.Axis.set_major_locator` - `matplotlib.ticker.FuncFormatter` - `matplotlib.ticker.MaxNLocator` .. _sphx_glr_download_gallery_ticks_tick_labels_from_values.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: tick_labels_from_values.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: tick_labels_from_values.py ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_