Python-Matplotlib可视化(10)——一文详解3D统计图的绘制

Python-Matplotlib可视化(10)——一文详解3D统计图的绘制

前言

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()

3D散点图

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼小辉丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值