'How to make a 3D surface plot from a 2D array?

I'm trying to make a 3D surface plot from a 2D array, using the values of my 2D array as the z value:

2D array

I want to do a surface plot like in the next pic:

3D surface plot

This is my code

import numpy as npimport matplotlib.pyplot as pltimport math as mtfrom mpl_toolkits import mplot3d

ax = plt.axes(projection="3D")

z = [[248, 236,289,300,267,225,266,265,259,279,269,335],[246,253,241,232,276,213,198,201,222,229,193,237],[182,180,200,192,233,211,227,220,174,187,181,197],[124,102,137,130,144,168,149,164,168,156,90,156],[117,124,133,119,155,140,133,120,130,134,138,102],[155,140,137,125,146,102,129,114,119,113,132,122],[104,117,119,138,137,118,117,128,131,133,119,133],[136,115,108,105,133,104,121,135,136,127,135,112],[84,87,93,116,123,110,90,123,112,115,92,107],[118,94,100,83,132,90,111,91,98,116,100,95],[101,76,115,121,108,102,94,80,83,104,101,81],[86,86,109,105,95,75,18,87,92,99,101,128]]
y = np.arange(len(z))x = np.arange(len(z[0]))
(x ,y) = np.meshgrid(x,y)
ax.plot3D(x,y,z)plt.show()

This is what I tried but gives me an error.



Solution 1:[1]

you need to use plot_surface:

ax = plt.axes(projection="3d")

z = np.array([[248, 236,289,300,267,225,266,265,259,279,269,335],[246,253,241,232,276,213,198,201,222,229,193,237],[182,180,200,192,233,211,227,220,174,187,181,197],[124,102,137,130,144,168,149,164,168,156,90,156],[117,124,133,119,155,140,133,120,130,134,138,102],[155,140,137,125,146,102,129,114,119,113,132,122],[104,117,119,138,137,118,117,128,131,133,119,133],[136,115,108,105,133,104,121,135,136,127,135,112],[84,87,93,116,123,110,90,123,112,115,92,107],[118,94,100,83,132,90,111,91,98,116,100,95],[101,76,115,121,108,102,94,80,83,104,101,81],[86,86,109,105,95,75,18,87,92,99,101,128]])

y = np.arange(len(z))
x = np.arange(len(z[0]))

(x ,y) = np.meshgrid(x,y)

ax.plot_surface(x,y,z)
plt.show()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 warped