matplotlib支持绘制三维线框图, 三维曲面图, 三维散点图. 需要使用axes3d提供3d坐标系.
from mpl_toolkits.mplot3d import axes3d
ax3d = mp.gca(projection='3d')
ax3d.plot_wireframe() # 绘制3d线框图
ax3d.plot_surface() # 绘制3d曲面图
ax3d.scatter() # 绘制3d散点图
三维线框图
ax3d.plot_wireframe(
x, y, # x,y网格点坐标矩阵
z, # z为每个坐标点的值
rstride=30, # 行跨距
cstride=30, # 列跨距
linewidth=1,
color=''
)
案例演示:
"""
三维线框图
"""
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
# 生成网格点坐标矩阵
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n),
np.linspace(-3, 3, n))
# 根据x,y 计算当前坐标下的z高度值
z = (1-x/2 + x**5 + y**3) * np.exp(-x**2 -y**2)
mp.figure('Wireframe', facecolor='lightgray')
ax3d = mp.gca(projection='3d')
ax3d.set_xlabel('X', fontsize=14)
ax3d.set_ylabel('Y', fontsize=14)
ax3d.set_zlabel('Z', fontsize=14)
ax3d.plot_wireframe(x, y, z, rstride=10,
cstride=10,color='dodgerblue')
mp.show()
三维曲面图
ax3d.plot_surface(
x, y, # x,y网格点坐标矩阵
z, # z为每个坐标点的值
rstride=30, # 行跨距
cstride=30, # 列跨距
cmap='jet'
)
案例演示:
"""
三维曲面图
"""
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
# 生成网格点坐标矩阵
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n),
np.linspace(-3, 3, n))
# 根据x,y 计算当前坐标下的z高度值
z = (1-x/2 + x**5 + y**3) * np.exp(-x**2 -y**2)
mp.figure('Surface', facecolor='lightgray')
ax3d = mp.gca(projection='3d')
ax3d.set_xlabel('X', fontsize=14)
ax3d.set_ylabel('Y', fontsize=14)
ax3d.set_zlabel('Z', fontsize=14)
ax3d.plot_surface(x, y, z, rstride=50,
cstride=50, cmap='jet')
mp.show()
ax3d.scatter(
x, y, z, # x,y,z 确定一组散点坐标
marker='', # 点型
s = 60, # 点的大小
edgecolor='', # 边缘色
facecolor='', # 填充色
zorder=3, # 绘制图层编号
c=d, # 设置过渡性颜色
cmap='jet' # 颜色映射
)
案例演示:
"""
三维散点图
"""
import numpy as np
import matplotlib.pyplot as mp
import mpl_toolkits.mplot3d as axes3d
n = 500
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
z = np.random.normal(0, 1, n)
d = np.sqrt(x**2 + y**2 + z**2)
mp.figure('3D Scatter')
ax3d = mp.gca(projection='3d')
ax3d.set_xlabel('X', fontsize=14)
ax3d.set_ylabel('Y', fontsize=14)
ax3d.set_zlabel('Z', fontsize=14)
ax3d.scatter(x, y, z, s=60, alpha=0.6,
c=d, cmap='jet')
mp.show()