Filled Contour Plots with Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

In this tutorial, we will learn how to create filled contour plots using the contourf method in the Matplotlib library. We will cover how to create filled contours with automatic and explicit levels, and how to set the colormap and extend settings.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) 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`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/contour_plots("`Contour Plots`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") 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 python/comments -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/with_statement -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} matplotlib/contour_plots -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/for_loops -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/lists -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/tuples -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/importing_modules -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/numerical_computing -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/data_visualization -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} python/build_in_functions -.-> lab-48626{{"`Filled Contour Plots with Matplotlib`"}} end

Import Libraries and Create Data

First, we need to import the necessary libraries and create some data to plot.

import matplotlib.pyplot as plt
import numpy as np

## Create data
origin = 'lower'
delta = 0.025
x = y = np.arange(-3.0, 3.01, 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

Create Filled Contour with Automatic Levels

Next, we will create a filled contour plot with automatic levels. We will use the contourf method with the cmap parameter set to plt.cm.bone to specify the colormap. We will also add contour lines with the contour method and pass in a subset of the contour levels used for the filled contours.

## Create filled contour with automatic levels
fig, ax = plt.subplots()
CS = ax.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin)
CS2 = ax.contour(CS, levels=CS.levels[::2], colors='r', origin=origin)

## Add title, axis labels, and colorbar
ax.set_title('Filled Contour with Automatic Levels')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
cbar = fig.colorbar(CS)
cbar.ax.set_ylabel('Z Label')
cbar.add_lines(CS2)

## Show plot
plt.show()

Create Filled Contour with Explicit Levels

Now, we will create a filled contour plot with explicit levels. We will use the contourf method with the levels parameter set to a list of values to specify the contour levels. We will also set the colormap to a list of colors and set the extend parameter to 'both' to show values outside the range of levels.

## Create filled contour with explicit levels
fig, ax = plt.subplots()
levels = [-1.5, -1, -0.5, 0, 0.5, 1]
CS = ax.contourf(X, Y, Z, levels, colors=('r', 'g', 'b'),
                 origin=origin, extend='both')
CS2 = ax.contour(X, Y, Z, levels, colors=('k',),
                 linewidths=(3,), origin=origin)

## Add title, axis labels, and colorbar
ax.set_title('Filled Contour with Explicit Levels')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
cbar = fig.colorbar(CS)
cbar.ax.set_ylabel('Z Label')

## Show plot
plt.show()

Set Colormap and Extend Settings

Finally, we will set the colormap and extend settings. We will use the with_extremes method to set the colors for values below and above the range of levels. We will also create four subplots to show the four possible extend settings: 'neither', 'both', 'min', and 'max'.

## Set colormap and extend settings
extends = ["neither", "both", "min", "max"]
cmap = plt.colormaps["winter"].with_extremes(under="magenta", over="yellow")

## Create subplots with different extend settings
fig, axs = plt.subplots(2, 2, layout="constrained")
for ax, extend in zip(axs.flat, extends):
    cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend, origin=origin)
    fig.colorbar(cs, ax=ax, shrink=0.9)
    ax.set_title("extend = %s" % extend)
    ax.locator_params(nbins=4)

## Show plot
plt.show()

Summary

In this tutorial, we learned how to create filled contour plots using the contourf method in the Matplotlib library. We covered how to create filled contours with automatic and explicit levels, and how to set the colormap and extend settings. With these skills, you can create beautiful and informative contour plots for your data.

Other Python Tutorials you may like