Plotting a 2d Array with mplot3d

Fourier picture Fourier · Jul 10, 2012 · Viewed 35.7k times · Source

I have a 2D numpy array and I want to plot it in 3D. I heard about mplot3d but I cant get to work properly

Here's an example of what I want to do. I have an array with the dimensions (256,1024). It should plot a 3D graph where the x axis is from 0 to 256 the y axis from 0 to 1024 and the z axis of the graph displays the value of of the array at each entry.

How do I go about this?

Answer

Chris picture Chris · Jul 10, 2012

It sounds like you are trying to create a surface plot (alternatively you could draw a wireframe plot or a filled countour plot.

From the information in the question, you could try something along the lines of:

import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Set up grid and test data
nx, ny = 256, 1024
x = range(nx)
y = range(ny)

data = numpy.random.random((nx, ny))

hf = plt.figure()
ha = hf.add_subplot(111, projection='3d')

X, Y = numpy.meshgrid(x, y)  # `plot_surface` expects `x` and `y` data to be 2D
ha.plot_surface(X, Y, data)

plt.show()

Obviously you need to choose more sensible data than using numpy.random in order to get a reasonable surface.