Gavin Wiggins

AboutNotesPhotos


Contour plot smoothing

Written on February 4, 2023

The example below generates a contour plot of sparse data.

import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter, zoom

# Get the data
data = np.loadtxt('data.txt')

# Create a contour plot of the original data
_, (ax1, ax2) = plt.subplots(ncols=2, tight_layout=True, figsize=[10, 4.8])
ax1.contour(data)
ax2.contourf(data)

original

The plot can be smoothed by using SciPy's zoom function or gaussian filter function. Input parameters for each function should be adjusted accordingly for the data.

# Resample the data with zoom then create contour plot
data2 = zoom(data, 3)

_, (ax1, ax2) = plt.subplots(ncols=2, tight_layout=True, figsize=[10, 4.8])
ax1.contour(data2)
ax2.contourf(data2)

zoom

# Resample data with gaussian filter then create contour plot
data3 = gaussian_filter(data, 0.7)

_, (ax1, ax2) = plt.subplots(ncols=2, tight_layout=True, figsize=[10, 4.8])
ax1.contour(data3)
ax2.contourf(data3)

gaussian

The contour plot examples in this article are based on a Stack Overflow post which is where the original data was obtained from.

Gavin Wiggins © 2024.
Made on a Mac with Genja. Hosted on GitHub Pages.