How can a contour plot be created in Matplotlib?

A contour plot is a useful graphical representation of 3-dimensional data that can be created in Matplotlib, a popular data visualization library in Python. To create a contour plot, the first step is to import the necessary libraries and data. Then, using the matplotlib.pyplot.contour() function, the data can be plotted as a series of contour lines, with each line representing a specific data point. The contour lines can be further customized by specifying the levels, colors, and labels. Additionally, the matplotlib.pyplot.contourf() function can be used to create a filled contour plot, where the space between the contour lines is colored based on the data values. With these functions and proper data manipulation, a contour plot can be easily generated in Matplotlib, providing a visual representation of the data’s varying levels and patterns.

Create a Contour Plot in Matplotlib


contour plot is a type of plot that allows us to visualize three-dimensional data in two dimensions by using contours.

You can create a contour plot in Matplotlib by using the following two functions:

The following examples show how to use these two functions in practice.

Example 1: Contour Plot in Matplotlib

Suppose we have the following data in Python:

import numpy as np

x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)

X, Y = np.meshgrid(x, y)
Z = np.sin(X*2+Y)*3 + np.cos(Y+5)

We can use the following code to create a contour plot for the data:

import matplotlib.pyplot as plt

plt.contour(X, Y, Z, colors='black')

Contour map in matplotlib

When a single color is used for the plot, the dashed lines represent negative values and the solid lines represent positive values.

An alternative is to specify a colormap using the cmap argument. We can also specify more lines to be used in the plot with the levels argument:

plt.contour(X, Y, Z, levels=30, cmap='Reds')

Matplotlib contour map with cmap

We chose to use the cmap ‘Reds’ but you can find a complete list of colormap options on the Matplotlib documentation page.

Example 2: Filled Contour Plot in Matplotlib

A filled contour plot is similar to a contour plot except that the spaces between the lines are filled.

plt.contourf(X, Y, Z, cmap='Reds')

Filled contour plot in Matplotlib

We can also use the colorbar() function to add a labeled color bar next to the plot:

plt.contourf(X, Y, Z, cmap='Reds')
plt.colorbar()

Contour map with colorbar in Matplotlib

You can find more Matplotlib tutorials here.

x