Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib - 3d surface from a rectangular array of heights

I am trying to plot some HDF data in matplotlib. After importing them using h5py, the data is stored in a form of array, like this:

array([[151, 176, 178],
       [121, 137, 130],
       [120, 125, 126])

In this case, x and y values are just the indexes of the array's fields, while z value is the value of specific field. In the (x,y,z) form it would look like:

(1,1,151)
(2,1,176)
(3,1,178)
(1,2,121)
...

and so on.

Is there an easy way to do a surface plot from this kind of data? I know I can change this to (x,y,z) tuples by iterating all over the array, but maybe it is not needed?

like image 310
Paweł Rumian Avatar asked Aug 01 '12 19:08

Paweł Rumian


People also ask

Can Matplotlib plot 3D images?

Among these, Matplotlib is the most popular choice for data visualization. While initially developed for plotting 2-D charts like histograms, bar charts, scatter plots, line plots, etc., Matplotlib has extended its capabilities to offer 3D plotting modules as well.

What function would we use to plot a 3D surface in Matplotlib?

To create the 3-dimensional surface plot the ax. plot_surface() function is used in matplotlib. In the above syntax, the X and Y mainly indicate a 2D array of points x and y while Z is used to indicate the 2D array of heights.


1 Answers

If you want a 3-d surface plot, you have to create the meshgrid first. You can try:

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

X = np.arange(1, 10)
Y = np.arange(1, 10)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot', linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

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

which will generate, enter image description here

However, if the only relevant information is in the z-values, you can simply use imshow. Here, z-values are represented by their color. You can achieve this by:

im = plt.imshow(Z, cmap='hot')
plt.colorbar(im, orientation='horizontal')
plt.show()

Which will give,

enter image description here

like image 141
imsc Avatar answered Sep 19 '22 15:09

imsc