Matplotlib Tick Formatter Tutorial

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Matplotlib is a widely used Python plotting library that produces high quality 2D and 3D graphs. In this lab, we will learn how to use tick formatters in Matplotlib.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/with_statement -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} matplotlib/importing_matplotlib -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} matplotlib/figures_axes -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/variables_data_types -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/strings -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/booleans -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/type_conversion -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/for_loops -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/lists -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/tuples -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/dictionaries -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/sets -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/function_definition -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/lambda_functions -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/importing_modules -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/using_packages -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/standard_libraries -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/data_visualization -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} python/build_in_functions -.-> lab-48987{{"`Matplotlib Tick Formatter Tutorial`"}} end

Importing Matplotlib and setting up the plot

First, we need to import the Matplotlib library and set up the plot. We will create an empty plot with one y-axis and one x-axis. We will also configure the axis to only show the bottom spine, set the tick positions, and define the tick length.

import matplotlib.pyplot as plt
from matplotlib import ticker

def setup(ax, title):
    """Set up common parameters for the Axes in the example."""
    ## only show the bottom spine
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines[['left', 'right', 'top']].set_visible(False)

    ## define tick positions
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
    ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))

    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.text(0.0, 0.2, title, transform=ax.transAxes,
            fontsize=14, fontname='Monospace', color='tab:blue')


fig, ax = plt.subplots(figsize=(8, 2))
setup(ax, "Tick Formatters")

Simple Formatting

In this step, we will show how to use a simple formatter by passing a string or function to ~.Axis.set_major_formatter or ~.Axis.set_minor_formatter. We will create two plots, one using a string formatter and the other using a function formatter.

fig0, axs0 = plt.subplots(2, 1, figsize=(8, 2))
fig0.suptitle('Simple Formatting')

## A ``str``, using format string function syntax, can be used directly as a
## formatter.  The variable ``x`` is the tick value and the variable ``pos`` is
## tick position.  This creates a StrMethodFormatter automatically.
setup(axs0[0], title="'{x} km'")
axs0[0].xaxis.set_major_formatter('{x} km')

## A function can also be used directly as a formatter. The function must take
## two arguments: ``x`` for the tick value and ``pos`` for the tick position,
## and must return a ``str``. This creates a FuncFormatter automatically.
setup(axs0[1], title="lambda x, pos: str(x-5)")
axs0[1].xaxis.set_major_formatter(lambda x, pos: str(x-5))

fig0.tight_layout()

Formatter Object Formatting

In this step, we will use .Formatter objects to format the ticks. We will create seven plots, each using a different formatter.

fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6))
fig1.suptitle('Formatter Object Formatting')

## Null formatter
setup(axs1[0], title="NullFormatter()")
axs1[0].xaxis.set_major_formatter(ticker.NullFormatter())

## StrMethod formatter
setup(axs1[1], title="StrMethodFormatter('{x:.3f}')")
axs1[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))

## FuncFormatter can be used as a decorator
@ticker.FuncFormatter
def major_formatter(x, pos):
    return f'[{x:.2f}]'

setup(axs1[2], title='FuncFormatter("[{:.2f}]".format)')
axs1[2].xaxis.set_major_formatter(major_formatter)

## Fixed formatter
setup(axs1[3], title="FixedFormatter(['A', 'B', 'C', ...])")
## FixedFormatter should only be used together with FixedLocator.
## Otherwise, one cannot be sure where the labels will end up.
positions = [0, 1, 2, 3, 4, 5]
labels = ['A', 'B', 'C', 'D', 'E', 'F']
axs1[3].xaxis.set_major_locator(ticker.FixedLocator(positions))
axs1[3].xaxis.set_major_formatter(ticker.FixedFormatter(labels))

## Scalar formatter
setup(axs1[4], title="ScalarFormatter()")
axs1[4].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))

## FormatStr formatter
setup(axs1[5], title="FormatStrFormatter('#%d')")
axs1[5].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))

## Percent formatter
setup(axs1[6], title="PercentFormatter(xmax=5)")
axs1[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))

fig1.tight_layout()

Displaying the Plots

Finally, we will display the plots using plt.show().

plt.show()

Summary

In this lab, we learned how to use tick formatters in Matplotlib by passing a string or function to ~.Axis.set_major_formatter or ~.Axis.set_minor_formatter, or by creating an instance of one of the various ~.ticker.Formatter classes and providing that to ~.Axis.set_major_formatter or ~.Axis.set_minor_formatter. We also learned how to set up a plot with tick positions, tick length, and a title.

Other Python Tutorials you may like