Matplotlib.pyplot.contourf() in Python

4 Jan 2025 | 3 min read

A Python module called Matplotlib is a mathematical and numerical extension for the NumPy library. Pyplot is a Matplotlib package that offers a MATLAB-like interface using a state-based interface.

In the following tutorial, we will understand what matplotlib.pyplot.contourf() Method is in Python and how to implement it.

Understanding the matplotlib.pyplot.contourf() Function

Plotting contours is done using the contourf() function included in the pyplot module of the matplotlib package. However, contourf creates contour lines, whereas contourf draws full contours.

Syntax:

Parameters: This method takes the following parameters:

  • X, Y: These are the coordinates that represent the location of values on the Z surface.
  • Z: This represents the height or value at each point, over which the contour lines are drawn.
  • levels: This parameter decides how many contour lines will be drawn and where they will be positioned on the plot.

The function c returns a QuadContourSet, which is an object that contains the information about the contour lines and regions created.

Below examples explain the matplotlib.pyplot.contourf() method in matplotlib.pyplot:

Example #1:

Explanation:

This program creates a 1000x1000 grid for x values from -5 to 5 and y values from -8 to 8 to make a contour plot with Matplotlib. It calculates Z = exp(X × Y), scales it by 50, and hides any values that are zero or negative.To make sure this is done, the initial 5x5 block of the grid is manually set to -1. After that, a colorbar is added to the plot as a point of reference and the masked array is displayed on a logarithmic colour scale using the "bone" colormap. The function's contour levels are shown throughout the designated x and y ranges in a plot that has a title.

Output:

Matplotlib.pyplot.contourf() in Python

Example #2:

Explanation:

This code creates a unique mesh grid by using np.linspace to produce grid values for x and y with varying ranges and resolutions. A modified trigonometric function that combines sine and cosine with various coefficients is used to obtain the z values. 'Blues' is a different colour map and a new set of hatching patterns that are added to plt.contourf to make a contour plot that looks different. To create a minor transparency effect, the alpha value is slightly changed to 0.9, and a colour bar is added to serve as a reference for the plot's colour scale. The general functioning and output are still in line with the original code despite the modifications.

Output:

Matplotlib.pyplot.contourf() in Python