# Matplotlib 三角曲面

``````import numpy as np
import matplotlib.pyplot as plt

width = 30
depth = 40
height = 50

def box(width, depth, height):
x = np.arange(width + 1)
y = np.arange(depth + 1)
z = np.arange(height + 1)

X0, Y0 = np.meshgrid(x, y)
Z0 = np.zeros((depth + 1, width + 1))

X1 = X0
Y1 = Y0
Z1 = Z0 + height

X2, Z2 = np.meshgrid(x, z)
Y2 = np.zeros((height + 1, width + 1))

X3 = X2
Y3 = Y2 + depth
Z3 = Z2

Y4, Z4 = np.meshgrid(y, z)
X4 = np.zeros((height + 1, depth + 1))

X5 = X4 + width
Y5 = Y4
Z5 = Z4

surfaces = [
[X0, Y0, Z0],
[X1, Y1, Z1],
[X2, Y2, Z2],
[X3, Y3, Z3],
[X4, Y4, Z4],
[X5, Y5, Z5]
]

ax = plt.axes(projection='3d')
for X, Y, Z in surfaces:
ax.plot_surface(X, Y, Z)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
leng = width + depth + height
ax.set_box_aspect((width / leng, depth / leng, height / leng))
plt.show()

box(width, depth, height)
``````

``````import numpy as np
import matplotlib.pyplot as plt

n = 20

points = np.random.rand(n, 3)
xs = points[:,0]
ys = points[:,1]
zs = points[:,2]

ax = plt.axes(projection='3d')
ax.plot_trisurf(xs, ys, zs)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
``````

`plot_trisurf` 需要的是一維陣列，分別代表所有座標的 x、y 與 z，這會繪製出以下的圖案：

``````import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

def function_grapher(f, x, y):
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

ax = plt.axes(projection='3d')
# plot_trisurf 需要一維陣列，因此透過 flatten 將二維陣列打平
ax.plot_trisurf(X.flatten(), Y.flatten(), Z.flatten(), cmap = cm.coolwarm)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_box_aspect((1, 1, 0.5))
plt.title('Axes3D Plot Surface')
plt.show()

def f(x, y):
n = np.sqrt(np.power(x, 2) + np.power(y, 2)) / 180 * np.pi
return np.cos(n) + np.cos(3 * n)

width = 200
step = 10

x = np.arange(-width, width, step)
y = np.arange(-width, width, step)

function_grapher(f, x, y)
``````

``````import numpy as np
import matplotlib.pyplot as plt

def tetrahedron(width):
n = width / (2 ** 0.5) * 0.5;

xs = np.array([n, -n,  n, -n])
ys = np.array([n,  n, -n, -n])
zs = np.array([n, -n, -n, n])

ax = plt.axes(projection='3d')
ax.plot_trisurf(xs, ys, zs, triangles = [[0, 1, 2], [1, 2, 3], [2, 3, 0], [3, 0, 1]])
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

width = 30
tetrahedron(width)
``````