Skip to content
Advertisement

How can i represent a 2d array in 3d in phython?

Im trying to represent an 2 dimensional array of a pyramid in the 3d space. In matlab i could just use the function mesh(). But in python im having a hard time doing it.

import numpy as np
import matplotlib.pyplot as plt

Pyramid = np.zeros([512, 512])
x = Pyramid.shape[0]
y = Pyramid.shape[1]

if x != y:
    print("ERROR: 'Not square'")
    exit()

for i in range(x // 2):
    for j in range(i, x - i):
        for h in range(i, x - i):
            Pyramid[j, h] = i

fig = plt.figure()
ax = plt.axes(projection="3d")
plt.show()

Advertisement

Answer

np.meshgrid() creates the grid coordinates. ax.plot_surface() plots a 3d height field.

import numpy as np
import matplotlib.pyplot as plt

Pyramid = np.zeros([512, 512])
x = Pyramid.shape[0]
y = Pyramid.shape[1]

for i in range(x // 2):
    for j in range(i, x - i):
        for h in range(i, x - i):
            Pyramid[j, h] = i
fig = plt.figure()
ax = plt.axes(projection="3d")
x2d, y2d = np.meshgrid(range(x), range(y))
ax.plot_surface(x2d, y2d, Pyramid)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('height')
plt.show()

plotting a height field

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement