Matplotlib Contour Image

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, you will learn how to create a contour image using Python's Matplotlib library. The contour image is a visualization technique that represents a three-dimensional surface using a two-dimensional plot. The contour image consists of contour lines, which are lines that connect points of equal value in the surface, and filled contours, which are regions between the contour lines.

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/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) 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/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) 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/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") matplotlib/PlotCustomizationGroup -.-> matplotlib/line_styles_colors("`Customizing Line Styles and Colors`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/contour_plots("`Contour Plots`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") 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/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") 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-48620{{"`Matplotlib Contour Image`"}} python/with_statement -.-> lab-48620{{"`Matplotlib Contour Image`"}} matplotlib/importing_matplotlib -.-> lab-48620{{"`Matplotlib Contour Image`"}} matplotlib/figures_axes -.-> lab-48620{{"`Matplotlib Contour Image`"}} matplotlib/heatmaps -.-> lab-48620{{"`Matplotlib Contour Image`"}} matplotlib/line_styles_colors -.-> lab-48620{{"`Matplotlib Contour Image`"}} matplotlib/contour_plots -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/variables_data_types -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/for_loops -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/lists -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/tuples -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/importing_modules -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/using_packages -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/standard_libraries -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/catching_exceptions -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/data_collections -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/numerical_computing -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/data_visualization -.-> lab-48620{{"`Matplotlib Contour Image`"}} python/build_in_functions -.-> lab-48620{{"`Matplotlib Contour Image`"}} end

Import Libraries

In this step, you will import the necessary libraries to create the contour image.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import cm

Define the Data

In this step, you will define the data to be plotted. The data is a two-dimensional array of values that represents the surface.

## Default delta is large because that makes it fast, and it illustrates
## the correct registration between image and contours.
delta = 0.5

extent = (-3, 4, -4, 3)

x = np.arange(-3.0, 4.001, delta)
y = np.arange(-4.0, 3.001, 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 the Contour Image

In this step, you will create the contour image by using Matplotlib's contour and contourf functions.

## Boost the upper limit to avoid truncation errors.
levels = np.arange(-2.0, 1.601, 0.4)

norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
cmap = cm.PRGn

fig, _axs = plt.subplots(nrows=2, ncols=2)
fig.subplots_adjust(hspace=0.3)
axs = _axs.flatten()

cset1 = axs[0].contourf(X, Y, Z, levels, norm=norm,
                        cmap=cmap.resampled(len(levels) - 1))
## It is not necessary, but for the colormap, we need only the
## number of levels minus 1.  To avoid discretization error, use
## either this number or a large number such as the default (256).

## If we want lines as well as filled regions, we need to call
## contour separately; don't try to change the edgecolor or edgewidth
## of the polygons in the collections returned by contourf.
## Use levels output from previous call to guarantee they are the same.

cset2 = axs[0].contour(X, Y, Z, cset1.levels, colors='k')

## We don't really need dashed contour lines to indicate negative
## regions, so let's turn them off.

for c in cset2.collections:
    c.set_linestyle('solid')

## It is easier here to make a separate call to contour than
## to set up an array of colors and linewidths.
## We are making a thick green line as a zero contour.
## Specify the zero level as a tuple with only 0 in it.

cset3 = axs[0].contour(X, Y, Z, (0,), colors='g', linewidths=2)
axs[0].set_title('Filled contours')
fig.colorbar(cset1, ax=axs[0])


axs[1].imshow(Z, extent=extent, cmap=cmap, norm=norm)
axs[1].contour(Z, levels, colors='k', origin='upper', extent=extent)
axs[1].set_title("Image, origin 'upper'")

axs[2].imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm)
axs[2].contour(Z, levels, colors='k', origin='lower', extent=extent)
axs[2].set_title("Image, origin 'lower'")

## We will use the interpolation "nearest" here to show the actual
## image pixels.
## Note that the contour lines don't extend to the edge of the box.
## This is intentional. The Z values are defined at the center of each
## image pixel (each color block on the following subplot), so the
## domain that is contoured does not extend beyond these pixel centers.
im = axs[3].imshow(Z, interpolation='nearest', extent=extent,
                   cmap=cmap, norm=norm)
axs[3].contour(Z, levels, colors='k', origin='image', extent=extent)
ylim = axs[3].get_ylim()
axs[3].set_ylim(ylim[::-1])
axs[3].set_title("Origin from rc, reversed y-axis")
fig.colorbar(im, ax=axs[3])

fig.tight_layout()
plt.show()

Display the Contour Image

In this step, you will display the contour image.

fig.tight_layout()
plt.show()

Summary

In this lab, you learned how to create a contour image using Python's Matplotlib library. You started by importing the necessary libraries, defining the data to be plotted, creating the contour image, and displaying the image. The contour image is a useful visualization technique that can be used to represent a three-dimensional surface using a two-dimensional plot.

Other Python Tutorials you may like