前言
Matplotlib 是 Python 的绘图库,它提供了一整套和 matlab 相似的命令 API,可以生成你所需的出版质量级别的图形,而制作3D图形的API与2D API非常相似。我们已经学习了一系列2D统计图的绘制,而在统计图中再添加一个维度可以展示更多信息。而且,在进行常规汇报或演讲时,3D图形也可以吸引更多的注意力。在本系列的最后一篇中,我们将探讨利用 Matplotlib 绘制三维统计图。
3D散点图
3D散点图的绘制方式与2D散点图基本相同。
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# Dataset generation
a, b, c = 10., 28., 8. / 3.
def lorenz_map(x, dt = 1e-2):
x_dt = np.array([a * (x[1] - x[0]), x[0] * (b - x[2]) - x[1], x[0] * x[1] - c * x[2]])
return x + dt * x_dt
points = np.zeros((2000, 3))
x = np.array([.1, .0, .0])
for i in range(points.shape[0]):
points[i], x = x, lorenz_map(x)
# Plotting
fig = plt.figure()
ax = fig.gca(projection = '3d')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('Lorenz Attractor a=%0.2f b=%0.2f c=%0.2f' % (a, b, c))
ax.scatter(points[:, 0], points[:, 1],points[:, 2], zdir = 'z', c = 'c')
plt.show()
Tips:按住鼠标左键移动鼠标可以旋转查看三维图形将旋转。
为了使用 Matplotlib 进行三维操作,我们首先需要导入 Matplotlib 的三维扩展:
from mpl_toolkits.mplot3d import Axes3D
对于三维绘图,需要创建一个Figure实例并附加一个 Axes3D
实例:
fig = plt.figure()
ax = fig.gca(projection='3d')
之后,三维散点图的绘制方式与二维散点图完全相同:
ax.scatter(points[:, 0], points[:, 1],points[:, 2], zdir = 'z', c = 'c')
Tips:需要调用 Axes3D 实例的 scatter() 方法,而非plt中的 scatter 方法。只有 Axes3D 中的 scatter() 方法才能解释三维数据。同时2D统计图中的注释也可以在3D图中使用,例如 set_title()、set_xlabel()、set_ylabel() 和 set_zlabel() 等。
同时可以通过使用 Axes3D.scatter()
的可选参数更改统计通的形状和颜色:
ax.scatter(points[:, 0], points