By JuanPablo


2013-09-12 12:50:35 8 Comments

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 ?

3 comments

@ImportanceOfBeingErnest 2017-04-14 07:54:56

The solution will depend on how the data is organized.

Data on regular grid

If the x and y data already define a grid, they can be easily reshaped to a quadrilateral grid. E.g.

#x  y  z
 4  1  3
 6  1  8
 8  1 -9
 4  2 10
 6  2 -1
 8  2 -8
 4  3  8
 6  3 -9
 8  3  0
 4  4 -1
 6  4 -8
 8  4  8 

can plotted as a contour using

import matplotlib.pyplot as plt
import numpy as np
x,y,z = np.loadtxt("data.txt", unpack=True)
plt.contour(x.reshape(4,3), y.reshape(4,3), z.reshape(4,3))

Arbitrary data

a. Interpolation

In case the data is not living on a quadrilateral grid, one can interpolate the data on a grid. One way to do so is scipy.interpolate.griddata

import numpy as np
from scipy.interpolate import griddata

xi = np.linspace(4, 8, 10)
yi = np.linspace(1, 4, 10)
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')
plt.contour(xi, yi, zi)

b. Non-gridded contour

Finally, one can plot a contour completely without the use of a quadrilateral grid. This can be done using tricontour.

plt.tricontour(x,y,z)

An example comparing the latter two methods is found on the matplotlib page.

@elyase 2013-09-12 12:56:34

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

@JuanPablo 2013-09-12 13:08:12

you import griddata from ? ... from scipy.interpolate import griddata or from matplotlib.mlab import griddata

@elyase 2013-09-12 13:12:23

@JuanPablo, ups, you are right, fixed(from matplotlib.mlab import griddata is the right one).

@Marti Nito 2018-11-26 12:17:31

from matplotlib.mlab import griddata is deprecated as of matplotlib 2.2

@endolith 2019-02-27 04:48:47

Deprecated since version 2.2: The griddata function was deprecated in Matplotlib 2.2 and will be removed in 3.1. Use scipy.interpolate.griddata instead.

@Gustavo Lopes 2019-06-07 16:58:06

Here plt.tricontourf(x, y, z, 15), what does the 15 means?

@David Zwicker 2013-09-12 12:55:14

contour expects regularly gridded data. You thus need to interpolate your data first:

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
import numpy.ma as ma
from numpy.random import uniform, seed
# make up some randomly distributed data
seed(1234)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# define grid.
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,100)
# grid the data.
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')
# contour the gridded data, plotting dots at the randomly spaced data points.
CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)
plt.colorbar() # draw colorbar
# plot data points.
plt.scatter(x,y,marker='o',c='b',s=5)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()

Note that I shamelessly stole this code from the excellent matplotlib cookbook

@JuanPablo 2013-09-12 13:50:00

when I use gridata of scipy.interpolate, the program are running a long time, this never stop.

@David Zwicker 2013-09-12 14:00:57

That of course depends on your data, which you didn't specify in your initial post. You should definitely try playing with the method argument of griddata. Try method="nearest", which should give the fastest interpolation.

Related Questions

Sponsored Content

42 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression?

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3872190 View
  • 3474 Score
  • 21 Answer
  • Tags:   python directory

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

45 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

25 Answered Questions

[SOLVED] How can I safely create a nested directory?

7 Answered Questions

[SOLVED] Manually raising (throwing) an exception in Python

  • 2010-01-12 21:07:40
  • TIMEX
  • 1639192 View
  • 2134 Score
  • 7 Answer
  • Tags:   python exception

10 Answered Questions

[SOLVED] How to access environment variable values?

11 Answered Questions

[SOLVED] Getting the last element of a list

  • 2009-05-30 19:28:53
  • Janusz
  • 1909931 View
  • 1920 Score
  • 11 Answer
  • Tags:   python list indexing

29 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3592784 View
  • 2954 Score
  • 29 Answer
  • Tags:   python list indexing

17 Answered Questions

[SOLVED] How to make a chain of function decorators?

Sponsored Content