Saturday, January 14, 2012

How to plot a function of two variables with matplotlib

In this post we will see how to visualize a function of two variables in two ways. First, we will create an intensity image of the function and, second, we will use the 3D plotting capabilities of matplotlib to create a shaded surface plot. So, let's go with the code:
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show

# the function that I'm going to plot
def z_func(x,y):
 return (1-(x**2+y**3))*exp(-(x**2+y**2)/2)
 
x = arange(-3.0,3.0,0.1)
y = arange(-3.0,3.0,0.1)
X,Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid

im = imshow(Z,cmap=cm.RdBu) # drawing the function
# adding the Contour lines with labels
cset = contour(Z,arange(-1,1.5,0.2),linewidths=2,cmap=cm.Set2)
clabel(cset,inline=True,fmt='%1.1f',fontsize=10)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('$z=(1-x^2+y^3) e^{-(x^2+y^2)/2}$')
show()
The script would have the following output:



And now we are going to use the values stored in X,Y and Z to make a 3D plot using the mplot3d toolkit. Here's the snippet:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, 
                      cmap=cm.RdBu,linewidth=0, antialiased=False)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()
And this is the result:

6 comments:

  1. i would like to see a demo using d3py from
    https://github.com/mikedewar/D3py/tree/v2

    ReplyDelete
  2. Which version of matplotlib do you use? I get attribute error

    --> 34 ax.zaxis.set_major_locator(LinearLocator(10))
    AttributeError: 'Axes3DSubplot' object has no attribute 'zaxis'

    ReplyDelete
  3. I made this code using matplotlib 1.1.0

    ReplyDelete
  4. Oh, I have 1.0.1. Thanks

    ReplyDelete
  5. Stack Overflow hints at how to do the 2nd example with matplotlib 0.99:

    http://stackoverflow.com/questions/3810865/need-help-with-matplotlib

    These small changes worked for me:

    http://pastebin.com/PnSMLqDD

    ReplyDelete
  6. Hello there! thank you very much indeed.

    Atte,

    Ignacio Aular

    :)

    ReplyDelete