Contour hatching in Matplotlib plot

Contour hatching in Matplotlib allows you to add visual patterns to filled contour plots, making it easier to distinguish between different regions. This is particularly useful for creating publication-ready plots or when working with grayscale images.

Basic Contour Hatching

Here's how to create a contour plot with different hatch patterns ?

import matplotlib.pyplot as plt
import numpy as np

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create coordinate arrays
x = np.linspace(-3, 5, 150)
y = np.linspace(-3, 5, 120)
X, Y = np.meshgrid(x, y)

# Generate sample data
Z = np.cos(X) + np.sin(Y)

# Create the plot
fig, ax = plt.subplots()

# Plot contour with hatching patterns
cs = ax.contourf(X, Y, Z, levels=8, 
                 hatches=['-', '/', '\', '//', '..', 'xx', '++', 'oo'],
                 cmap='gray', extend='both', alpha=0.7)

# Add colorbar
fig.colorbar(cs)
ax.set_title('Contour Plot with Hatching Patterns')

plt.show()

Available Hatch Patterns

Matplotlib supports various hatching patterns. Here's a demonstration of different patterns ?

import matplotlib.pyplot as plt
import numpy as np

# Create simple data
x = np.linspace(0, 4, 5)
y = np.linspace(0, 4, 5)
X, Y = np.meshgrid(x, y)
Z = X + Y

fig, axes = plt.subplots(2, 4, figsize=(12, 6))
axes = axes.flatten()

# Different hatch patterns
patterns = ['-', '/', '\', '|', '+', 'x', 'o', '.']
titles = ['Horizontal', 'Forward Slash', 'Backward Slash', 'Vertical', 
          'Plus', 'Cross', 'Circles', 'Dots']

for i, (pattern, title) in enumerate(zip(patterns, titles)):
    cs = axes[i].contourf(X, Y, Z, levels=5, hatches=[pattern], 
                         colors=['lightblue'], alpha=0.7)
    axes[i].set_title(f'{title} ({pattern})')
    axes[i].set_aspect('equal')

plt.tight_layout()
plt.show()

Combining Multiple Patterns

You can combine different hatch patterns for each contour level ?

import matplotlib.pyplot as plt
import numpy as np

# Create more complex data
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = np.exp(-(X**2 + Y**2))

fig, ax = plt.subplots(figsize=(8, 6))

# Use different hatches for different levels
cs = ax.contourf(X, Y, Z, levels=[0, 0.2, 0.4, 0.6, 0.8, 1.0],
                 hatches=['...', '///', '\\\', '+++', 'xxx'],
                 colors=['lightcoral', 'lightblue', 'lightgreen', 'yellow', 'orange'],
                 alpha=0.6)

# Add contour lines for clarity
ax.contour(X, Y, Z, levels=[0, 0.2, 0.4, 0.6, 0.8, 1.0], colors='black', linewidths=0.5)

plt.colorbar(cs)
ax.set_title('Multiple Hatch Patterns in One Plot')
ax.set_xlabel('X')
ax.set_ylabel('Y')

plt.show()

Customizing Hatch Density

You can control the density of hatching by repeating pattern characters ?

import matplotlib.pyplot as plt
import numpy as np

# Sample data
theta = np.linspace(0, 2*np.pi, 100)
r = np.linspace(0, 1, 50)
R, THETA = np.meshgrid(r, theta)
Z = R * np.sin(3*THETA)

fig, axes = plt.subplots(1, 3, figsize=(12, 4))

# Different densities
densities = ['/', '//', '////']
titles = ['Low Density', 'Medium Density', 'High Density']

for i, (density, title) in enumerate(zip(densities, titles)):
    cs = axes[i].contourf(R*np.cos(THETA), R*np.sin(THETA), Z, 
                         levels=10, hatches=[density], 
                         cmap='viridis', alpha=0.8)
    axes[i].set_title(title)
    axes[i].set_aspect('equal')

plt.tight_layout()
plt.show()

Key Parameters

Parameter Description Example Values
hatches List of hatch patterns ['-', '/', '\', '++']
alpha Transparency level 0.5 to 1.0
colors Fill colors ['red', 'blue']
cmap Colormap 'gray', 'viridis'

Conclusion

Contour hatching in Matplotlib provides an effective way to distinguish between different regions in your plots. Use different patterns like /, \, +, and . to create visually appealing and informative contour plots. Combine hatching with transparency and colors for the best results.

Updated on: 2026-03-25T22:56:50+05:30

868 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements