Matplotlib 绘制 3D 图形使用 mplot3d Toolkit 即 mplot3d 工具包,在 matplotlib 中使用 mplot3d 工具包。绘制 3D 图可以通过创建子图,然后指定 projection 参数 为 3d 即可,返回的 ax 为 Axes3D 对象。mplot3d 官方学习文档
导入包:
from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from mpl_toolkits.mplot3d import Axes3D
绘图全过程:
import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from mpl_toolkits.mplot3d import Axes3D import numpy as np
fig = plt.figure()
# 指定图形类型是 3d 类型 ax = fig.add_subplot(projection='3d')
# 构造数据 X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R)
# Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
呈现效果:
3D 帽子图2
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure() # 指定图形类型为 3d 类型 ax = fig.add_subplot(111, projection='3d') # X, Y value X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25)
# 设置 x-y 平面的网格 X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) # height value Z = np.sin(R)
# For each set of style and range settings, plot n random points in the box # defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh]. for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]: xs = randrange(n, 23, 32) ys = randrange(n, 0, 100) zs = randrange(n, zlow, zhigh) ax.scatter(xs, ys, zs, c=c, marker=m)