当前位置:首页 > Python > 正文

Python Axes3D 3D图形绘制完全指南 | 数据可视化教程

Python Axes3D 3D图形绘制完全指南

学习使用Matplotlib的Axes3D模块创建专业的3D散点图、曲面图、线图和柱状图

为什么使用Axes3D进行3D绘图?

Matplotlib是Python中最流行的绘图库,而其Axes3D模块提供了强大的3D数据可视化功能。3D图形在以下场景特别有用:

  • 可视化具有三个变量的数据集(如物理模拟中的x,y,z坐标)
  • 展示复杂数学函数的曲面
  • 分析时间序列数据的三维关系
  • 创建科学数据的交互式可视化
  • 呈现机器学习模型的多维特征空间

安装与基础配置

开始前,确保安装了最新版Matplotlib:

pip install matplotlib numpy

基础3D绘图模板:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# 创建图形和3D坐标轴
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# 在此处添加绘图代码

# 设置标签和标题
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Visualization')

plt.show()

3D散点图

散点图非常适合展示三维空间中点的分布:

# 生成随机数据
np.random.seed(42)
n_points = 300
x = np.random.normal(0, 1, n_points)
y = np.random.normal(0, 1, n_points)
z = np.random.normal(0, 1, n_points)
colors = np.random.rand(n_points)
sizes = 100 * np.random.rand(n_points)

# 创建3D散点图
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

scatter = ax.scatter(x, y, z, 
                    c=colors, 
                    s=sizes,
                    cmap='viridis',
                    alpha=0.7,
                    edgecolor='k')

# 添加颜色条
fig.colorbar(scatter, ax=ax, shrink=0.5, label='Value')

ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('3D Scatter Plot with Color and Size Variation')

plt.show()
Python Axes3D 3D图形绘制完全指南 | 数据可视化教程 3D绘图  Matplotlib 3D散点图 3D曲面图 Python数据可视化 2025 第1张

3D散点图示例 - 展示三维空间中的数据点分布

3D曲面图

曲面图适合可视化数学函数或连续数据:

# 创建数据网格
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))  # 波纹函数

# 创建3D曲面图
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection='3d')

# 绘制曲面
surf = ax.plot_surface(X, Y, Z, 
                      cmap='plasma',
                      edgecolor='none',
                      antialiased=True,
                      rstride=2, 
                      cstride=2,
                      alpha=0.9)

# 添加颜色条
fig.colorbar(surf, ax=ax, shrink=0.5, label='Z Value')

# 添加等高线投影
ax.contour(X, Y, Z, 15, zdir='z', offset=-1.5, cmap='coolwarm')

ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('3D Surface Plot of Ripple Function')
ax.set_zlim(-1.5, 1.5)

plt.show()
Python Axes3D 3D图形绘制完全指南 | 数据可视化教程 3D绘图  Matplotlib 3D散点图 3D曲面图 Python数据可视化 2025 第2张

3D曲面图示例 - 展示数学函数的立体形态

3D线图与柱状图

3D线图

# 创建螺旋线数据
theta = np.linspace(0, 8 * np.pi, 500)
z = np.linspace(0, 10, 500)
x = np.cos(theta) * (1 + 0.5 * z)
y = np.sin(theta) * (1 + 0.5 * z)

# 创建3D线图
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

ax.plot(x, y, z, 
        color='#e74c3c', 
        linewidth=2.5,
        label='3D Spiral')

# 添加标记点
ax.scatter(x[::50], y[::50], z[::50], 
           s=50, 
           c='#2ecc71',
           edgecolor='k',
           label='Points')

ax.legend()
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_title('3D Spiral Line Plot')
ax.view_init(25, -60)  # 设置视角

3D柱状图

# 准备柱状图数据
x_pos = np.arange(5)
y_pos = np.arange(6)
x, y = np.meshgrid(x_pos, y_pos)
x, y = x.ravel(), y.ravel()
z = np.zeros_like(x)
dx = dy = 0.8 * np.ones_like(z)
dz = np.random.rand(len(z)) * 5

# 创建3D柱状图
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')

colors = plt.cm.jet(dz / dz.max())
ax.bar3d(x, y, z, dx, dy, dz, color=colors, shade=True)

ax.set_xlabel('X Category')
ax.set_ylabel('Y Category')
ax.set_zlabel('Value')
ax.set_title('3D Bar Chart')
ax.set_xticks(x_pos + 0.4)
ax.set_yticks(y_pos + 0.4)
ax.set_xticklabels(['A', 'B', 'C', 'D', 'E'])
ax.set_yticklabels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])

plt.show()

高级应用与交互

交互式旋转

使用%matplotlib notebook在Jupyter中启用交互模式:

# 在Jupyter Notebook中启用交互模式
%matplotlib notebook

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ... 绘图代码 ...
plt.show()

现在可以点击并拖动图形进行旋转!

动画效果

创建旋转视角的动画:

from matplotlib.animation import FuncAnimation

def update(frame):
    ax.view_init(30, frame)
    return fig,

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ... 绘图代码 ...

ani = FuncAnimation(fig, update, 
                   frames=np.arange(0, 360, 2),
                   interval=50)
plt.show()

这将创建平滑旋转的3D图形动画。

© 2023 Python数据可视化教程 | 使用Matplotlib Axes3D进行3D绘图

发表评论