Contour Plots in Matplotlib
Learn how to create contour plots using Matplotlib. Understand contour(), contourf(), contour levels, contour labels, filled contours, colormaps and contour visualisation with practical Python examples.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand contour plots and their applications.
- Create contour plots using contour().
- Create filled contour plots using contourf().
- Understand X, Y and Z data in contour plotting.
- Control contour levels.
- Add labels to contour lines.
- Apply different colormaps to contour plots.
- Customise contour line colours and widths.
- Add colorbars to contour plots.
- Create contour plots using real-world data.
2. Introduction to Contour Plots
A contour plot is a graphical representation of three-dimensional numerical data on a two-dimensional plane. It uses lines or filled colour regions to represent locations having the same Z value.
Contour plots are useful for understanding how a numerical value changes across two variables. They are commonly used in scientific visualisation, engineering, geography and mathematical analysis.
What is a Contour Line?
A contour line connects points that have the same numerical value. For example, a weather contour map may connect locations having the same temperature or atmospheric pressure.
X Coordinates
+
Y Coordinates
|
v
Calculate Z Values
|
v
Contour Levels
|
v
Contour Lines / Filled Regions
Conceptual illustration of contour lines representing different numerical levels.
3. Understanding X, Y and Z Data
A contour plot requires three important datasets: X coordinates, Y coordinates and Z values. The Z values represent the numerical measurements at each X and Y coordinate.
Understanding the Three Variables
| Variable | Meaning |
|---|---|
| X | Horizontal coordinate values. |
| Y | Vertical coordinate values. |
| Z | Numerical values calculated for each X and Y position. |
Example: Creating X, Y and Z Values
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
print(X.shape)
print(Y.shape)
print(Z.shape)
Output
(100, 100)
(100, 100)
(100, 100)
The meshgrid() function creates
coordinate matrices from the X and Y arrays.
The Z array calculates a numerical value for
every coordinate position.
np.meshgrid()
is a common way to prepare coordinate data.
4. Creating a Basic Contour Plot
Matplotlib provides the contour() function
to create contour lines. It connects points that have
the same Z value.
Basic Syntax
plt.contour(X, Y, Z, levels=None)
Example: Simple Contour Plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
plt.contour(X, Y, Z)
plt.title('Basic Contour Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
Output
A contour plot is displayed with multiple contour lines.
Each contour line represents a constant Z value.
The contour lines form circular patterns around the centre
because Z = X² + Y².
Understanding the Output
In this example, Z is calculated by adding the square of X and the square of Y. Values are smaller near the centre and increase as we move away from the centre. Therefore, the contour lines form approximately circular patterns.
5. Controlling Contour Levels
Contour levels define the numerical values at which contour lines are drawn. You can specify the number of levels or provide a list of exact values.
5.1 Using Number of Levels
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
plt.contour(X, Y, Z, levels=10)
plt.title('Contour Plot with 10 Levels')
plt.show()
Output
A contour plot is displayed with approximately 10
automatically selected contour levels.
5.2 Using Custom Levels
You can provide a list of numerical values to control exactly where contour lines are drawn.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
levels = [5, 10, 20, 30, 40]
plt.contour(
X,
Y,
Z,
levels=levels
)
plt.title('Custom Contour Levels')
plt.show()
Output
A contour plot is displayed using the specified levels:
5, 10, 20, 30 and 40.
Only the available contour levels within the data range
are drawn.
6. Customising Contour Lines
You can customise contour lines using parameters
such as colors, linewidths
and linestyles.
6.1 Changing Line Colours
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
plt.contour(
X,
Y,
Z,
levels=10,
colors='blue'
)
plt.title('Blue Contour Lines')
plt.show()
Output
A contour plot is displayed with blue contour lines.
The contour levels represent different Z values.
6.2 Changing Line Widths
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
plt.contour(
X,
Y,
Z,
levels=8,
colors='darkgreen',
linewidths=2
)
plt.title('Contour Lines with Custom Width')
plt.show()
Output
A contour plot is displayed using dark green contour lines.
The lines have a width of 2 points.
6.3 Changing Line Styles
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
plt.contour(
X,
Y,
Z,
levels=8,
colors='red',
linestyles='dashed'
)
plt.title('Dashed Contour Lines')
plt.show()
Output
A contour plot is displayed with red dashed contour lines.
| Parameter | Purpose |
|---|---|
colors |
Sets the contour line colours. |
linewidths |
Controls the thickness of contour lines. |
linestyles |
Controls solid, dashed or dotted line styles. |
levels |
Defines the contour levels. |
7. Adding Labels to Contour Lines
Contour lines can be labelled with their numerical
values using the plt.clabel() function.
These labels help users identify the value represented
by each contour line.
Example: Adding Contour Labels
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
contours = plt.contour(
X,
Y,
Z,
levels=8,
colors='blue'
)
plt.clabel(
contours,
inline=True,
fontsize=10
)
plt.title('Contour Plot with Labels')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
Output
A contour plot is displayed with blue contour lines.
Numerical values are displayed along the contour lines.
Each label identifies the corresponding contour level.
Important clabel() Parameters
| Parameter | Description |
|---|---|
inline |
Places labels inline with contour lines. |
fontsize |
Controls the label font size. |
fmt |
Controls the label number format. |
colors |
Sets the label colour. |
8. Creating Filled Contour Plots
The contourf() function creates filled
contour plots. Instead of drawing only contour lines,
it fills the regions between contour levels with colours.
Basic Syntax
plt.contourf(X, Y, Z, levels=None, cmap=None)
Example: Basic Filled Contour Plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
plt.contourf(
X,
Y,
Z,
levels=15,
cmap='viridis'
)
plt.title('Filled Contour Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.colorbar(label='Z Values')
plt.show()
Output
A filled contour plot is displayed using the viridis colormap.
Different regions represent different Z value ranges.
A colorbar explains the numerical values represented by colours.
Conceptual comparison of line contours and filled contours.
9. Difference Between contour() and contourf()
Both functions are used to create contour visualisations, but they display the data differently.
| Feature | contour() | contourf() |
|---|---|---|
| Purpose | Draws contour lines. | Creates filled contour regions. |
| Appearance | Line-based representation. | Colour-filled representation. |
| Colour mapping | Can colour contour lines. | Colours the regions between levels. |
| Labels | Can use clabel(). | Usually uses a colorbar to explain regions. |
| Common usage | Showing exact contour boundaries. | Showing numerical distribution across an area. |
Example: Both Functions Together
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
filled = plt.contourf(
X,
Y,
Z,
levels=15,
cmap='viridis'
)
lines = plt.contour(
X,
Y,
Z,
levels=15,
colors='black',
linewidths=0.5
)
plt.clabel(lines, inline=True, fontsize=8)
plt.colorbar(filled, label='Z Values')
plt.title('Filled Contours with Contour Lines')
plt.show()
Output
A filled contour plot is displayed using the viridis colormap.
Black contour lines are drawn over the filled regions.
Numerical labels are displayed on the contour lines.
A colorbar explains the Z value range.
contour() when contour boundaries
are important. Use contourf() when
you want to show the distribution of values using
coloured regions.
10. Applying Colormaps to Contour Plots
Matplotlib allows you to apply different colormaps
to filled contour plots using the cmap
parameter.
Example: Different Colormaps
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
colormaps = ['viridis', 'plasma', 'coolwarm', 'inferno']
fig, axes = plt.subplots(2, 2, figsize=(9, 7))
for ax, cmap_name in zip(axes.flat, colormaps):
contour = ax.contourf(
X,
Y,
Z,
levels=15,
cmap=cmap_name
)
ax.set_title(cmap_name)
plt.tight_layout()
plt.show()
Output
A figure containing four filled contour plots is displayed.
Each plot uses a different colormap:
viridis, plasma, coolwarm and inferno.
The same numerical data is represented using different
colour schemes.
11. Adding Colorbars to Contour Plots
A colorbar explains the numerical values represented by the colours in a filled contour plot. It helps users understand the value range of each coloured region.
Example: Filled Contour with Colorbar
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
contour = plt.contourf(
X,
Y,
Z,
levels=20,
cmap='plasma'
)
plt.colorbar(
contour,
label='Z Values'
)
plt.title('Contour Plot with Colorbar')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()
Output
A filled contour plot is displayed using the plasma colormap.
A vertical colorbar appears beside the plot.
The colorbar label is Z Values.
Customising Colorbar Ticks
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
contour = plt.contourf(
X,
Y,
Z,
levels=10,
cmap='viridis'
)
cbar = plt.colorbar(contour)
cbar.set_ticks([0, 20, 40, 60])
cbar.set_label('Measurement')
plt.title('Custom Contour Colorbar')
plt.show()
Output
A filled contour plot is displayed with a colorbar.
The colorbar shows selected ticks at 0, 20, 40 and 60.
The colorbar label is Measurement.
12. Contour Levels and Extensions
Contour plots can use selected levels to divide
numerical data into ranges. The extend
parameter of contourf() can indicate values outside
the specified contour levels.
Example: Filled Contour with Extensions
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
levels = [5, 10, 20, 30, 40]
contour = plt.contourf(
X,
Y,
Z,
levels=levels,
cmap='coolwarm',
extend='both'
)
plt.colorbar(contour, label='Z Values')
plt.title('Contour Plot with Extensions')
plt.show()
Output
A filled contour plot is displayed using selected contour levels.
The colorbar indicates values outside the selected range
using extension markers at both ends.
Common extension values are neither,
min, max and both.
13. Contour Plot Using Mathematical Functions
Contour plots are commonly used to visualise mathematical functions. You can calculate Z values using different mathematical expressions and display their patterns.
Example: Sine and Cosine Function
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2 * np.pi, 2 * np.pi, 150)
y = np.linspace(-2 * np.pi, 2 * np.pi, 150)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
contour = plt.contourf(
X,
Y,
Z,
levels=20,
cmap='coolwarm'
)
plt.colorbar(contour, label='Function Values')
plt.title('Sine and Cosine Contour Plot')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.show()
Output
A filled contour plot is displayed.
The plot represents the function sin(X) * cos(Y).
Different coloured regions show positive and negative values.
A colorbar displays the function value range.
14. Complete Practical Example
In this example, we create a temperature distribution contour plot. The X and Y coordinates represent locations, while Z represents temperature values.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
X, Y = np.meshgrid(x, y)
Z = (
30
+ 10 * np.sin(X / 2)
+ 8 * np.cos(Y / 2)
)
fig, ax = plt.subplots(figsize=(9, 6))
filled = ax.contourf(
X,
Y,
Z,
levels=20,
cmap='coolwarm'
)
lines = ax.contour(
X,
Y,
Z,
levels=10,
colors='black',
linewidths=0.6
)
ax.clabel(
lines,
inline=True,
fontsize=8
)
fig.colorbar(
filled,
ax=ax,
label='Temperature (°C)'
)
ax.set_title('Temperature Distribution')
ax.set_xlabel('X Location')
ax.set_ylabel('Y Location')
plt.tight_layout()
plt.show()
Output
A temperature distribution contour plot is displayed.
Different colours represent different temperature ranges.
Black contour lines indicate constant temperature values.
Numerical labels are displayed on selected contour lines.
A colorbar displays the temperature range in degrees Celsius.
What We Learned
We created coordinate arrays using NumPy and calculated temperature values using a mathematical function. The contourf() function displayed filled colour regions, while contour() added boundary lines. The clabel() function displayed contour values and colorbar() explained the temperature range.
15. Common Mistakes and Solutions
| Common Mistake | Solution |
|---|---|
| X, Y and Z arrays have incompatible shapes. | Use np.meshgrid() and check array shapes. |
| Contour lines are not displayed clearly. | Adjust levels, colours and linewidths. |
| Filled contour regions are not visible. | Use contourf() instead of contour(). |
| Contour labels are missing. | Use plt.clabel() with the contour object. |
| Colour mapping is not clear. | Choose a suitable colormap and add a colorbar. |
| Custom levels are outside the data range. | Check minimum and maximum Z values. |
| Contour plot looks crowded. | Reduce the number of contour levels. |
| Contour values are difficult to read. | Adjust label font size and line width. |
16. Practical Activity
Activity 1: Create a Basic Contour Plot
Generate X and Y coordinate arrays using np.linspace() and np.meshgrid(). Calculate Z = X**2 + Y**2 and create a contour plot.
Activity 2: Customise Contour Levels
Create a contour plot using custom levels such as 5, 10, 20, 30 and 40.
Activity 3: Style Contour Lines
Change contour line colours, widths and line styles.
Activity 4: Create Filled Contours
Use contourf() with viridis, plasma and coolwarm colormaps.
Activity 5: Add Contour Labels
Use plt.clabel() to display numerical values along contour lines.
Activity 6: Temperature Distribution
Create a temperature distribution using a mathematical function. Add filled contours, contour lines and a colorbar.
17. Practice Questions
- What is a contour plot in Matplotlib?
- What is a contour line?
- What are X, Y and Z values in contour plotting?
- What is the purpose of np.meshgrid()?
- What is the difference between contour() and contourf()?
- How can you control contour levels?
- How can you change contour line colours?
- What is the purpose of plt.clabel()?
- How can you apply a colormap to a filled contour plot?
- How can you add a colorbar to a contour plot?
- What is the purpose of the extend parameter?
- Where are contour plots used in real-world applications?
Summary
Contour plots are used to represent three-dimensional numerical data on a two-dimensional plane. They use contour lines or filled colour regions to show locations having the same numerical values.
Matplotlib provides the contour() function to create contour lines. The contourf() function creates filled contour plots in which different numerical ranges are represented using colours.
Contour plotting requires X, Y and Z data. The NumPy meshgrid() function is commonly used to create coordinate matrices for mathematical functions.
The levels parameter controls where contour lines or filled regions are created. Custom colours, line widths and line styles can be used to improve the appearance of contour plots.
The clabel() function adds numerical labels to contour lines. Colormaps and colorbars help users understand the values represented by filled regions.
Contour plots are useful in scientific analysis, engineering, temperature distribution, geography, mathematical functions and many other applications.
Understanding contour() and contourf() allows you to create detailed visualisations of numerical data and identify important patterns across two-dimensional coordinate spaces.