Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib contour() / contourf() Function

Matplotlib contour() / contourf() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

contour() Draw contour lines (outlines),contourf() Draw filled contours.

Both are used to visualize 2D scalar fields (such as terrain maps, temperature fields, pressure fields, etc.).

Function definition

pyplot interface

matplotlib.pyplot.contour(*args, **kwargs)
matplotlib.pyplot.contourf(*args, **kwargs)

Axes interface

Axes.contour(X, Y, Z, levels=None, **kwargs)
Axes.contourf(X, Y, Z, levels=None, **kwargs)

Parameter Description

Parameters Type Description
X, Y 2D array-like or 1D array The x and y coordinates of the grid points. If 1D arrays are passed, they are automatically expanded via meshgrid
Z 2D array-like The function value (height) at each grid point, with the same shape as X, Y
levels int or array-like Contour levels: an integer means automatically generate N levels, an array means specific level values
colors color or list Contour line color (for contour)
cmap str or Colormap Colormap (for contourf), such as 'viridis', 'terrain'
alpha float Transparency, 0-1
linewidths float or list Line width (for contour)
linestyles str or list Line style (for contour), such as 'solid', 'dashed'
extend str Color handling for values outside the levels range: 'neither'/'both'/'min'/'max'
antialiased bool Whether to enable antialiasing (contourf), default True

clabel() supplementary notes

clabel() Used to add numeric labels on contour lines.

Axes.clabel(CS, levels=None, **kwargs)

Usage examples

Example 1: Basic contour vs. filled contour comparison

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a 2D grid and function values

x

=

np.

linspace

(

3

,

3

,

100

)

y

=

np.

linspace

(

3

,

3

,

100

)

X

,

Y

=

np.

meshgrid

(

x

,

y

)

Z

=

np.

sin

(

X

)

cos

(

Y

)

 

2D function

fig

,

(

ax1

,

ax2

)

=

plt.

subplots

(

1

,

2

,

figsize

=

(

12

,

5

)

,

                                layout

=

'constrained'

)

Left: contour lines (contour)

cs1

=

ax1.

contour

(

X

,

Y

,

Z

,

levels

=

10

,

cmap

=

'viridis'

)

ax1.

clabel

(

cs1

,

inline

=

True

,

fontsize

=

8

)

 

Add labels

ax1.

set_title

(

'contour() - Line Contours'

)

Right plot: Filled contour (contourf)

cs2

=

ax2.

contourf

(

X

,

Y

,

Z

,

levels

=

15

,

cmap

=

'RdYlBu'

)

fig.

colorbar

(

cs2

,

ax

=

ax2

,

label

=

'Value'

)

Overlay boundary lines

ax2.

contour

(

X

,

Y

,

Z

,

levels

=

15

,

colors

=

'black'

,

linewidths

=

0.3

)

ax2.

set_title

(

'contourf() - Filled Contours'

)

for

ax

in

[

ax1

,

ax2

]

:

    ax.

set_xlabel

(

'X'

)

    ax.

set_ylabel

(

'Y'

)

plt.

show

(

)

Example 2: Custom levels

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

5

,

5

,

150

)

y

=

np.

linspace

(

5

,

5

,

150

)

X

,

Y

=

np.

meshgrid

(

x

,

y

)

Gaussian hill

Z

=

np.

exp

(

(

(

X-

1

)

**

2

2

)

/

4

)

    np.

exp

(

(

(

X+

1

)

**

2

2

)

/

3

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

7

,

5

)

,

layout

=

'constrained'

)

Custom levels: 0.1 to 1.0, with a spacing of 0.1

custom_levels

=

np.

arange

(

0.1

,

1.1

,

0.1

)

cs

=

ax.

contourf

(

X

,

Y

,

Z

,

levels

=

custom_levels

,

                 cmap

=

'YlOrRd'

,

extend

=

'both'

)

cbar

=

fig.

colorbar

(

cs

,

ax

=

ax

,

label

=

'Height'

)

ax.

contour

(

X

,

Y

,

Z

,

levels

=

custom_levels

,

           colors

=

'black'

,

linewidths

=

0.5

)

ax.

set_title

(

'Custom Levels Contour'

)

ax.

set_xlabel

(

'X'

)

ax.

set_ylabel

(

'Y'

)

plt.

show

(

)

Example 3: Terrain map style (terrain colormap)

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

4

,

4

,

200

)

y

=

np.

linspace

(

4

,

4

,

200

)

X

,

Y

=

np.

meshgrid

(

x

,

y

)

Simulated terrain: two peaks + one valley

Z

=

3

exp

(

(

(

X+

2

)

**

2

2

)

/

3

)

   

2

exp

(

(

(

X-

1

)

**

2

(

Y-

1

)

**

2

)

/

2

)

   

1

exp

(

(

(

X+

0.5

)

**

2

(

Y-

2

)

**

2

)

/

1.5

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

6

)

,

layout

=

'constrained'

)

terrain colormap to simulate a terrain map

cs

=

ax.

contourf

(

X

,

Y

,

Z

,

levels

=

20

,

cmap

=

'terrain'

,

extend

=

'both'

)

fig.

colorbar

(

cs

,

ax

=

ax

,

label

=

'Elevation'

,

shrink

=

0.8

)

ax.

contour

(

X

,

Y

,

Z

,

levels

=

20

,

colors

=

'black'

,

linewidths

=

0.3

,

           alpha

=

0.4

)

ax.

set_title

(

'Terrain-style Contour Map'

)

ax.

set_xlabel

(

'X (km)'

)

ax.

set_ylabel

(

'Y (km)'

)

plt.

show

(

)

print

(

"runoob: terrain contour displayed"

)


Common questions

When to use contour vs. contourf?

contour(): suitable for seeing clear boundary lines, such as pressure isobars.

contourf(): suitable for showing continuously varying fields, such as temperature distribution.

A common practice is to overlay both: contourf fills the colors, contour overlays the boundary lines.

Must X and Y be 2D?

No. If 1D arrays are passed as X and Y, matplotlib automatically calls np.meshgrid(X, Y) to generate a 2D grid. Z must match the shape after meshgrid.

Matplotlib Reference Documentation Matplotlib Reference Documentation