How to smooth matplotlib contour plot?

PythonMatplotlib

Python Problem Overview


I have numpy array with this shape: (33,10). When I plot contour I get ugly image like this: enter image description here

while contour() doesn't seem to have any argument about smoothing or some sort of interpolation feature.

I somehow expected that tool which offers contour plot should offer smoothing too.
Is there straight forward way to do it in MPL?

Python Solutions


Solution 1 - Python

As others have already pointed out, you need to interpolate your data.

There are a number of different ways to do this, but for starters, consider scipy.ndimage.zoom.

As a quick exmaple:

import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt

data = np.loadtxt('data.txt')

# Resample your data grid by a factor of 3 using cubic spline interpolation.
data = scipy.ndimage.zoom(data, 3)

plt.contour(data)
plt.show()

enter image description here

Solution 2 - Python

In case your data is sparse, Joe Kingtons answer is great.

In case your data is noisy, you should consider filtering it instead:

from numpy import loadtxt
from scipy.ndimage.filters import gaussian_filter
from matplotlib.pyplot import contour, show

sigma = 0.7 # this depends on how noisy your data is, play with it!
data = loadtxt('data.txt')
data = gaussian_filter(data, sigma)
contour(data)
show()

enter image description here

Solution 3 - Python

There is no easy way to get a smooth contour. An alternative is to try imshow. You can look here for other possibilities.

import pylab as plt
import numpy as np

Z=np.loadtxt('data.txt')
plt.subplot(131)
plt.imshow(Z,interpolation='nearest')

plt.subplot(132)
plt.imshow(Z)

plt.subplot(133)
plt.imshow(Z,interpolation='gaussian')

plt.show()

enter image description here

Solution 4 - Python

Try to smooth your dataset with a gaussian_filter. See example for more info.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthetaView Question on Stackoverflow
Solution 1 - PythonJoe KingtonView Answer on Stackoverflow
Solution 2 - PythonwsjView Answer on Stackoverflow
Solution 3 - PythonimscView Answer on Stackoverflow
Solution 4 - PythonymnView Answer on Stackoverflow