Contourf and Log Color Scale

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to use the contourf function in Matplotlib to create filled contour plots with a logarithmic color scale. We will use a dataset with positive and negative values to demonstrate this feature.

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/DataStructuresGroup(["`Data Structures`"]) 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`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/contour_plots("`Contour Plots`") 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`") subgraph Lab Skills python/comments -.-> lab-48628{{"`Contourf and Log Color Scale`"}} python/with_statement -.-> lab-48628{{"`Contourf and Log Color Scale`"}} matplotlib/importing_matplotlib -.-> lab-48628{{"`Contourf and Log Color Scale`"}} matplotlib/figures_axes -.-> lab-48628{{"`Contourf and Log Color Scale`"}} matplotlib/contour_plots -.-> lab-48628{{"`Contourf and Log Color Scale`"}} python/lists -.-> lab-48628{{"`Contourf and Log Color Scale`"}} python/tuples -.-> lab-48628{{"`Contourf and Log Color Scale`"}} python/importing_modules -.-> lab-48628{{"`Contourf and Log Color Scale`"}} python/numerical_computing -.-> lab-48628{{"`Contourf and Log Color Scale`"}} python/data_visualization -.-> lab-48628{{"`Contourf and Log Color Scale`"}} end

Import the necessary libraries

We need to import the following libraries:

  • matplotlib.pyplot for creating plots and visualizations
  • numpy for generating the dataset
import matplotlib.pyplot as plt
import numpy as np

Generate the dataset

We will generate a dataset with positive and negative values using numpy:

N = 100
x = np.linspace(-3.0, 3.0, N)
y = np.linspace(-2.0, 2.0, N)

X, Y = np.meshgrid(x, y)

## A low hump with a spike coming out.
## Needs to have z/colour axis on a log scale, so we see both hump and spike.
## A linear scale only shows the spike.
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
z = Z1 + 50 * Z2

## Put in some negative values (lower left corner) to cause trouble with logs:
z[:5, :5] = -1

## The following is not strictly essential, but it will eliminate
## a warning.  Comment it out to see the warning.
z = ma.masked_where(z <= 0, z)

Create the plot

We will use the contourf function to create a filled contour plot with a logarithmic color scale:

fig, ax = plt.subplots()
cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r)

cbar = fig.colorbar(cs)

plt.show()

Customize the plot

We can customize the plot by adding labels, titles, and changing the color map:

fig, ax = plt.subplots()
cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.coolwarm)

ax.set_title('Contourf Plot with Log Color Scale')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

cbar = fig.colorbar(cs)

plt.show()

Summary

In this lab, we learned how to use the contourf function in Matplotlib to create filled contour plots with a logarithmic color scale. We also learned how to customize the plot by adding labels, titles, and changing the color map.

Other Python Tutorials you may like