Plotting 3-tuple data points in a surface / contour plot using matplotlib


I have some surface data that is generated by an external program as XYZ values. I want to create the following graphs, using matplotlib:

  • Surface plot
  • Contour plot
  • Contour plot overlayed with a surface plot

I have looked at several examples for plotting surfaces and contours in matplotlib - however, the Z values seems to be a function of X and Y i.e. Y ~ f(X,Y).

I assume that I will somehow need to transform my Y variables, but I have not seen any example yet, that shows how to do this.

So, my question is this: given a set of (X,Y,Z) points, how may I generate Surface and contour plots from that data?

BTW, just to clarify, I do NOT want to create scatter plots. Also although I mentioned matplotlib in the title, I am not averse to using rpy(2), if that will allow me to create these charts.

7/22/2010 8:16:49 PM

Accepted Answer

for do a contour plot you need interpolate your data to a regular grid

a quick example:

>>> xi = linspace(min(X), max(X))
>>> yi = linspace(min(Y), max(Y))
>>> zi = griddata(X, Y, Z, xi, yi)
>>> contour(xi, yi, zi)

for the surface

>>> from mpl_toolkits.mplot3d import Axes3D
>>> fig = figure()
>>> ax = Axes3D(fig)
>>> xim, yim = meshgrid(xi, yi)
>>> ax.plot_surface(xim, yim, zi)
>>> show()

>>> help(meshgrid(x, y))
    Return coordinate matrices from two coordinate vectors.
    >>> X, Y = np.meshgrid([1,2,3], [4,5,6,7])
    >>> X
    array([[1, 2, 3],
           [1, 2, 3],
           [1, 2, 3],
           [1, 2, 3]])
    >>> Y
    array([[4, 4, 4],
           [5, 5, 5],
           [6, 6, 6],
           [7, 7, 7]])

contour in 3D

>>> fig = figure()
>>> ax = Axes3D(fig)
>>> ax.contour(xi, yi, zi) # ax.contourf for filled contours
>>> show()
6/10/2010 9:57:13 AM

With pandas and numpy to import and manipulate data, with matplot.pylot.contourf to plot the image

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata


#Get the original data

#Through the unstructured data get the structured data by interpolation
xi = np.linspace(x.min()-1, x.max()+1, 100)
yi = np.linspace(y.min()-1, y.max()+1, 100)
zi = griddata(x, y, z, xi, yi, interp='linear')

#Plot the contour mapping and edit the parameter setting according to your data (
CS = plt.contourf(xi, yi, zi, 5, levels=[0,50,100,1000],colors=['b','y','r'],vmax=abs(zi).max(), vmin=-abs(zi).max())

#Save the mapping and save the image

Example Image

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow