Home » Tutorial on Creating Contour Plots in Matplotlib

Tutorial on Creating Contour Plots in Matplotlib

Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]

Contour plots are useful for visualizing three-dimensional data on a two-dimensional plane. They represent levels or “contours” that correspond to different heights or values of a variable.

This makes contour plots particularly useful for representing topographical maps, potential fields, and heat maps.

In this tutorial, we’ll explore how to create and customize contour plots in Matplotlib with examples covering the basics, filled contours, adding color bars, labeled contours, multiple contour sets, and more.

1. Basic Contour Plot

A contour plot is created using the contour function in Matplotlib, which requires x, y, and z data.

import numpy as np
import matplotlib.pyplot as plt

# Generate sample data
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Create a basic contour plot
plt.figure(figsize=(8, 6))
plt.contour(X, Y, Z, levels=10, colors='black')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Basic Contour Plot")
plt.show()

In this example:

  • X and Y are created using np.meshgrid to represent a grid of x and y values.
  • Z contains the function values (sin(sqrt(x^2 + y^2))).
  • plt.contour(X, Y, Z, levels=10, colors='black') creates a contour plot with 10 contour levels in black.

2. Filled Contour Plot

A filled contour plot is similar to a contour plot, but it fills the spaces between the contours with color.

# Filled contour plot
plt.figure(figsize=(8, 6))
plt.contourf(X, Y, Z, levels=10, cmap='viridis')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Filled Contour Plot")
plt.colorbar(label="Z value")
plt.show()

In this example:

  • plt.contourf() creates filled contours.
  • cmap='viridis' applies a colormap to the filled regions.
  • plt.colorbar() adds a color bar that represents the Z values for each color.

3. Adding Color Bars to Contour Plots

A color bar provides a legend for the contour colors, making it easier to interpret the values represented by each contour level.

# Contour plot with color bar
plt.figure(figsize=(8, 6))
contours = plt.contour(X, Y, Z, levels=10, cmap='coolwarm')
plt.colorbar(contours, label="Z value")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Contour Plot with Color Bar")
plt.show()

In this example:

  • contours = plt.contour() stores the contour plot in the contours variable.
  • plt.colorbar(contours) adds a color bar, showing the mapping between colors and Z values.

4. Customizing Contour Levels

You can define specific contour levels by passing a list to the levels parameter.

# Custom contour levels
levels = [-0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75]

plt.figure(figsize=(8, 6))
plt.contour(X, Y, Z, levels=levels, colors='black')
plt.contourf(X, Y, Z, levels=levels, cmap='coolwarm', alpha=0.5)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Contour Plot with Custom Levels")
plt.colorbar(label="Z value")
plt.show()

In this example:

  • levels=levels specifies custom contour levels, allowing us to control exactly where contours appear.
  • plt.contourf() adds filled contours, using alpha=0.5 to make them partially transparent.

5. Labeled Contours

Labels can be added to contour lines to indicate the specific Z values at each contour level.

# Contour plot with labels
plt.figure(figsize=(8, 6))
contours = plt.contour(X, Y, Z, levels=10, colors='black')
plt.clabel(contours, inline=True, fontsize=10)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Contour Plot with Labels")
plt.show()

In this example:

  • plt.clabel(contours, inline=True, fontsize=10) adds labels to the contour lines.
  • inline=True places the labels directly on the lines, and fontsize=10 sets the label size.

6. Multiple Contour Sets on the Same Plot

You can overlay multiple contour sets on the same plot to compare different contour levels or highlight specific ranges.

# Multiple contour sets
plt.figure(figsize=(8, 6))

# Filled contour plot
plt.contourf(X, Y, Z, levels=10, cmap='Blues', alpha=0.6)

# Overlay another contour set with different levels
plt.contour(X, Y, Z, levels=[-0.5, 0, 0.5], colors='black', linewidths=1.5)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Multiple Contour Sets")
plt.colorbar(label="Z value")
plt.show()

In this example:

  • plt.contourf() creates a filled contour plot.
  • plt.contour() overlays a second contour set with selected levels, creating a layered effect.

7. Contour Plot with Different Line Styles

You can customize the line style and width of contour lines to differentiate between levels.

# Contour plot with custom line styles
plt.figure(figsize=(8, 6))
contours = plt.contour(X, Y, Z, levels=10, colors='black', linestyles='dashed', linewidths=1.5)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Contour Plot with Custom Line Styles")
plt.colorbar(contours, label="Z value")
plt.show()

In this example:

  • linestyles='dashed' uses dashed lines for the contours.
  • linewidths=1.5 increases the thickness of the lines.

8. Logarithmic Contour Plot

For data that spans several orders of magnitude, a logarithmic scale on the contour levels can improve readability.

# Generate data that spans multiple orders of magnitude
Z_log = np.exp(Z)  # Exponentiate Z values for large range

# Logarithmic contour plot
plt.figure(figsize=(8, 6))
plt.contourf(X, Y, Z_log, levels=np.logspace(0, 3, 10), cmap='plasma')
plt.colorbar(label="Z value (log scale)")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Logarithmic Contour Plot")
plt.show()

In this example:

  • np.exp(Z) creates values that vary over several orders of magnitude.
  • levels=np.logspace(0, 3, 10) uses a logarithmic scale for the contour levels.

9. Contour Plot with Annotations

Annotations can help highlight specific points or features on a contour plot. You can annotate a peak, valley, or other point of interest.

# Annotate a specific point on the contour plot
plt.figure(figsize=(8, 6))
plt.contourf(X, Y, Z, levels=10, cmap='viridis')
plt.colorbar(label="Z value")
plt.scatter(0, 0, color='red')  # Mark the origin
plt.annotate("Center Point", xy=(0, 0), xytext=(-2, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05))
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Contour Plot with Annotation")
plt.show()

In this example:

  • plt.annotate() labels a specific point on the plot.
  • arrowprops adds an arrow pointing to the annotated location.

10. Contour Plot with Subplots

If you want to display multiple contour plots for comparison, you can use subplots to create side-by-side views.

# Generate another data set for comparison
Z2 = np.cos(np.sqrt(X**2 + Y**2))

# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

# First contour plot
contour1 = ax1.contourf(X, Y, Z, levels=10, cmap='viridis')
fig.colorbar(contour1, ax=ax1, label="Z value")
ax1.set_title("Sine Function Contour")

# Second contour plot
contour2 = ax2.contourf(X, Y, Z2, levels=10, cmap='plasma')
fig.colorbar(contour2, ax=ax2, label="Z value")
ax2.set_title("Cosine Function Contour")

plt.suptitle("Comparison of Two Contour Plots")
plt.show()

In this example:

  • plt.subplots(1, 2) creates two subplots side by side for comparison.
  • Each subplot has a separate color bar and title.

11. Three-Dimensional Contour Plot (Contour on Surface Plot)

For a three-dimensional effect

, you can overlay a contour plot on a 3D surface plot, which can be achieved using contour3D from mpl_toolkits.mplot3d.

from mpl_toolkits.mplot3d import Axes3D

# 3D contour plot
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none', alpha=0.7)
ax.contour3D(X, Y, Z, levels=10, cmap='cool', linestyles='solid')

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface with Contours")
plt.show()

In this example:

  • ax.plot_surface() creates a 3D surface plot.
  • ax.contour3D() adds 3D contour lines to the surface plot.

Summary

In this tutorial, we covered a variety of ways to create and customize contour plots using Matplotlib:

  1. Basic Contour Plot to display contour lines.
  2. Filled Contour Plot to fill regions between contour levels with color.
  3. Adding Color Bars for better interpretation.
  4. Customizing Contour Levels to set specific ranges.
  5. Labeled Contours to add value labels directly on the contours.
  6. Multiple Contour Sets to overlay multiple contour groups.
  7. Custom Line Styles and Widths to differentiate levels.
  8. Logarithmic Contour Plot for data spanning large ranges.
  9. Adding Annotations to highlight important features.
  10. Contour Plot with Subplots for side-by-side comparison.
  11. 3D Contour Plot for a three-dimensional effect with Axes3D.

These examples demonstrate the versatility of contour plots for visualizing complex data distributions and relationships in 2D and 3D, providing detailed control over visual aspects for effective data presentation.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More