首页 > 解决方案 > 如何使用matplotlib python创建3点的3d三角形

问题描述

我想创建一个像这样的 3D 图:它来自一个方程。但我对制作这个没有任何想法,我已经尝试了几次,但结果只是一个点,正如你在结果图像上看到的那样。对不起,我的英语不好。以下是预期结果:

在此处输入图像描述

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import style

plt.figure('SPLTV',figsize=(10,5))
custom=plt.subplot(121,projection='3d')
#x-2y+z=6
x1=np.array([1,-2,1])
y1=np.array([5,3,7])
z1=np.array([6])
custom.scatter(x1,y1,z1)
custom.set_xlabel('X')
custom.set_ylabel('Y')
custom.set_zlabel('Z')
plt.show()

这是我的结果:

在此处输入图像描述

标签: pythonmatplotlib

解决方案


你需要的是Poly3DCollection. 考虑对您的代码进行以下修改:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d.art3d import Poly3DCollection  # appropriate import to draw 3d polygons
from matplotlib import style

plt.figure('SPLTV',figsize=(10,5))
custom=plt.subplot(121,projection='3d')
#x-2y+z=6
x1=np.array([1, -2, 1])
y1=np.array([5, 3, 7])
z1=np.array([0, 0, 6])  # z1 should have 3 coordinates, right?
custom.scatter(x1,y1,z1)

# 1. create vertices from points
verts = [list(zip(x1, y1, z1))]
# 2. create 3d polygons and specify parameters
srf = Poly3DCollection(verts, alpha=.25, facecolor='#800000')
# 3. add polygon to the figure (current axes)
plt.gca().add_collection3d(srf)

custom.set_xlabel('X')
custom.set_ylabel('Y')
custom.set_zlabel('Z')
plt.show()

推荐阅读