Filled Contour Plots with Hatching

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to create filled contour plots with hatched patterns using Python's Matplotlib library. Contour plots are used to display three-dimensional data in two dimensions. They are particularly useful for visualizing data that has peaks and valleys, such as topographical data.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) 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/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlotCustomizationGroup -.-> matplotlib/line_styles_colors("`Customizing Line Styles and Colors`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") 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/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills python/comments -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} matplotlib/importing_matplotlib -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} matplotlib/figures_axes -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} matplotlib/line_styles_colors -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} matplotlib/legend_config -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} matplotlib/contour_plots -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/variables_data_types -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/for_loops -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/lists -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/tuples -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/dictionaries -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/importing_modules -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/data_collections -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/numerical_computing -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} python/data_visualization -.-> lab-48627{{"`Filled Contour Plots with Hatching`"}} end

Import Libraries

We begin by importing the necessary libraries. In this lab, we will be using NumPy and Matplotlib.

import matplotlib.pyplot as plt
import numpy as np

Create Data

Next, we will create some sample data to plot. In this example, we will create a 2D grid of x and y values and use them to calculate z values.

## invent some numbers, turning the x and y arrays into simple
## 2d arrays, which make combining them together easier.
x = np.linspace(-3, 5, 150).reshape(1, -1)
y = np.linspace(-3, 5, 120).reshape(-1, 1)
z = np.cos(x) + np.sin(y)

Simplest Hatched Plot with a Colorbar

In this step, we will create the simplest hatched plot with a colorbar. We will use the contourf function to create the filled contour plot and specify the hatches using the hatches parameter.

fig1, ax1 = plt.subplots()
cs = ax1.contourf(x, y, z, hatches=['-', '/', '\\', '//'],
                  cmap='gray', extend='both', alpha=0.5)
fig1.colorbar(cs)

Plot of Hatches without Color with a Legend

In this step, we will create a plot of hatches without color and add a legend. We will use the contour function to create the contour lines and the contourf function to specify the hatches without color.

fig2, ax2 = plt.subplots()
n_levels = 6
ax2.contour(x, y, z, n_levels, colors='black', linestyles='-')
cs = ax2.contourf(x, y, z, n_levels, colors='none',
                  hatches=['.', '/', '\\', None, '\\\\', '*'],
                  extend='lower')

## create a legend for the contour set
artists, labels = cs.legend_elements(str_format='{:2.1f}'.format)
ax2.legend(artists, labels, handleheight=2, framealpha=1)

Display the Plots

Finally, we will display the plots using the show function.

plt.show()

Summary

In this lab, we learned how to create filled contour plots with hatched patterns using Matplotlib. We used the contour and contourf functions to create the plots and specified the hatches using the hatches parameter. We also added a colorbar and legend to our plots.

Other Python Tutorials you may like