Make contour of scatter

JuanPablo picture JuanPablo · Sep 12, 2013 · Viewed 28.9k times · Source

In python, If I have a set of data

x, y, z

I can make a scatter with

import matplotlib.pyplot as plt
plt.scatter(x,y,c=z)

How I can get a plt.contourf(x,y,z) of the scatter ?

Answer

elyase picture elyase · Sep 12, 2013

You can use tricontourf as suggested in case b. of this other answer:

import matplotlib.tri as tri
import matplotlib.pyplot as plt

plt.tricontour(x, y, z, 15, linewidths=0.5, colors='k')
plt.tricontourf(x, y, z, 15)

Old reply:

Use the following function to convert to the format required by contourf:

from numpy import linspace, meshgrid
from matplotlib.mlab import griddata

def grid(x, y, z, resX=100, resY=100):
    "Convert 3 column data to matplotlib grid"
    xi = linspace(min(x), max(x), resX)
    yi = linspace(min(y), max(y), resY)
    Z = griddata(x, y, z, xi, yi)
    X, Y = meshgrid(xi, yi)
    return X, Y, Z

Now you can do:

X, Y, Z = grid(x, y, z)
plt.contourf(X, Y, Z)

enter image description here