How to Use the Matplotlib Contourf() Function in Python



In this article, you will learn how to use the Matplotlib contourf() function in Python.

Matplotlib Contourf() Function

Matplotlib is a powerful visualization library in Python that allows you to create various types of graphs and plots. One such plot is the contour plot, which is used to represent 3-dimensional data in 2-dimensional space.

The contourf() function in Matplotlib is used to create filled contour plots. It takes in three arguments: the x-values, the y-values, and the z-values. Here’s an example code snippet that demonstrates how to use contourf():

import numpy as np
import matplotlib.pyplot as plt

# Create data
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create a filled contour plot
plt.contourf(X, Y, Z)
plt.colorbar()  # Add a colorbar  # Show the plot

In this example, we first create some data using NumPy’s meshgrid() function. We then create a 2-dimensional array Z with the values of sin(sqrt(X^2 + Y^2)). Finally, we use the contourf() function to create a filled contour plot of this data. The colorbar() function is used to add a colorbar to the plot, which helps to interpret the colors in the plot.

You can also customize the plot by specifying additional arguments to the contourf() function. For example, you can set the number of contour levels using the levels argument, or set the color scheme using the cmap argument. Here’s an example that demonstrates how to set these arguments:

# Create a filled contour plot with custom arguments
plt.contourf(X, Y, Z, levels=20, cmap='RdYlBu')
plt.title('Contour Plot Example')

In this example, we set the number of contour levels to 20 and the color scheme to the ‘RdYlBu’ colormap. We also added a title and labels to the x-axis and y-axis of the plot.

These are just a few examples of how to use the contourf() function in Matplotlib. With a little experimentation, you can create many different types of contour plots to suit your needs.