Customized Matplotlib Contour Labeling

PythonPythonBeginner
Practice Now

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

Introduction

In this tutorial, we will learn how to create contour labels in Matplotlib. Contour labels are used to label the contours in a contour plot. This tutorial will cover some advanced techniques for creating custom contour labels.

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 matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/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`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/contour_plots("`Contour Plots`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/matplotlib_config("`Customizing Matplotlib Configurations`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} matplotlib/figures_axes -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} matplotlib/contour_plots -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} matplotlib/event_handling -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} matplotlib/matplotlib_config -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/booleans -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/conditional_statements -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/for_loops -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/lists -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/tuples -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/dictionaries -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/function_definition -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/importing_modules -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/numerical_computing -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/data_visualization -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} python/build_in_functions -.-> lab-48621{{"`Customized Matplotlib Contour Labeling`"}} end

Define our surface

We will start by defining our surface using numpy and matplotlib. This will give us a dataset to work with.

import matplotlib.pyplot as plt
import numpy as np

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

Make contour labels with custom level formatters

We will now create contour labels with custom level formatters. This will allow us to format the labels in a specific way. In this case, we will remove trailing zeros and add a percent sign.

def fmt(x):
    s = f"{x:.1f}"
    if s.endswith("0"):
        s = f"{x:.0f}"
    return rf"{s} \%" if plt.rcParams["text.usetex"] else f"{s} %"

fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10)

Label contours with arbitrary strings using a dictionary

We can also label contours with arbitrary strings using a dictionary. This will allow us to label the contours with custom labels. In this example, we will use a list of strings to label the contours.

fig1, ax1 = plt.subplots()
CS1 = ax1.contour(X, Y, Z)

fmt = {}
strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']
for l, s in zip(CS1.levels, strs):
    fmt[l] = s

ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10)

Use a Formatter

We can also use a formatter to format the contour labels. This will allow us to format the labels in a specific way. In this example, we will use a LogFormatterMathtext to format the labels.

fig2, ax2 = plt.subplots()
CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator())
fmt = ticker.LogFormatterMathtext()
fmt.create_dummy_axis()
ax2.clabel(CS2, CS2.levels, fmt=fmt)
ax2.set_title("$100^Z$")

plt.show()

Summary

In this tutorial, we learned how to create contour labels in Matplotlib. We covered some advanced techniques for creating custom contour labels, including custom level formatters, labeling contours with arbitrary strings, and using a formatter to format the contour labels. These techniques can be useful for creating visualizations that are both informative and aesthetically pleasing.

Other Python Tutorials you may like