Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot 3D function as 2D colormap in python?

Are there any python libraries that will let me plot z = f(x,y) where z is represented as the color in a densely rasterized image (as opposed to the color of a bunch of scatterplot points) ? If so, what function do I use?

It looks like some of the contour functions in matplotlib.pyplot come close to what I want, but they draw contour lines and I don't want that.

like image 319
Ian Goodfellow Avatar asked Mar 03 '11 20:03

Ian Goodfellow


2 Answers

here's a concrete simple example (works also for functions which can't take matrix arguments for x and y):

# the function to be plotted
def func(x,y):    
    # gives vertical color bars if x is horizontal axis
    return x

import pylab

# define the grid over which the function should be plotted (xx and yy are matrices)
xx, yy = pylab.meshgrid(
    pylab.linspace(-3,3, 101),
    pylab.linspace(-3,3, 111))

# indexing of xx and yy (with the default value for the
# 'indexing' parameter of meshgrid(..) ) is as follows:
#
#   first index  (row index)    is y coordinate index
#   second index (column index) is x coordinate index
#
# as required by pcolor(..)

# fill a matrix with the function values
zz = pylab.zeros(xx.shape)
for i in range(xx.shape[0]):
    for j in range(xx.shape[1]):
        zz[i,j] = func(xx[i,j], yy[i,j])

# plot the calculated function values
pylab.pcolor(xx,yy,zz)

# and a color bar to show the correspondence between function value and color
pylab.colorbar()

pylab.show() 
like image 128
Andre Holzner Avatar answered Oct 15 '22 23:10

Andre Holzner


Take a look at the documentation for pcolor or imshow in matplotlib.

Another good place to start is take a look at the matplotlib gallery and see if there is a plot type that matches what you are looking for and then use the sample code as a jumping off point for your own work:

http://matplotlib.sourceforge.net/gallery.html

like image 22
JoshAdel Avatar answered Oct 15 '22 23:10

JoshAdel