python绘制3d图-Python绘制3D图形
3D图形在数据分析、数据建模、图形和图像处理等领域中都有着⼴泛的应⽤,下⾯将给⼤家介绍⼀下如何使⽤python进⾏3D图形的绘制,包括3D散点、3D表⾯、3D轮廓、3D直线(曲线)以及3D⽂字等的绘制。
准备⼯作:
python中绘制3D图形,依旧使⽤常⽤的绘图模块matplotlib,但需要安装mpl_toolkits⼯具包,安装⽅法如下:windows命令⾏进⼊到python安装⽬录下的Scripts⽂件夹下,执⾏: pip install --upgrade matplotlib即可;linux环境下直接执⾏该命令。
安装好这个模块后,即可调⽤mpl_tookits下的mplot3d类进⾏3D图形的绘制。
下⾯以实例进⾏说明。
1、3D表⾯形状的绘制
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Make data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.s(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.s(np.size(u)), np.cos(v))
# Plot the surface
ax.plot_surface(x, y, z, color='b')
plt.show()
球表⾯,结果如下:
2、3D直线(曲线)的绘制
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = a(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
这段代码⽤于绘制⼀个螺旋状3D曲线,结果如下:
3、绘制3D轮廓
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = a(projection='3d')
linspace numpyX, Y, Z = _test_data(0.05)
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, lwarm) cset = ax.contour(X, Y, Z, zdir='x', offset=-40, lwarm) cset = ax.contour(X, Y, Z, zdir='y', offset=40, lwarm) ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
plt.show()
绘制结果如下:
4、绘制3D直⽅图
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
# Construct arrays for the anchor positions of the 16 bars.
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid # with indexing='ij'.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)
# Construct arrays with the dimensions for the 16 bars.
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
plt.show()
绘制结果如下:
5、绘制3D⽹状线
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
X, Y, Z = _test_data(0.05)
# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show()
绘制结果如下:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论