Matplotlib 绘制 3D 曲面动画
程序员文章站
2022-02-05 19:26:53
...
Matplotlib 绘制 3D 曲面动画
本文介绍如何使用 Python 中的 Matplotlib 库来绘制动态的 3D 曲面。示例如下:
环境
- macOS 11.6
- python 3.8
数据
以上图中左边的数据为例:
- 30 × 32 × 32 30\times 32 \times 32 30×32×32
思路
- 加载依赖
- 加载数据
- 转换数据
- 定义动画更新的函数
- 绘制 3D 曲面
- 保存为
gif
代码
加载依赖
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import cm
加载数据
数据下载地址(123 KB)
z = np.load('./data.npy')
转换数据
x
轴和y
轴的数据。
x = np.linspace(0, 31, 32)
y = x
x, y = np.meshgrid(x, y)
定义数据更新数据
函数的三个参数:
- 动画要更新的次数(帧),可以当作是数据的索引
- 更新的数据
- 画布
def update_map(num, z, plot):
plot[0].remove()
plot[0] = ax.plot_surface(x, y, z[num], cmap=cm.Oranges, linewidth=0)
然后定义画布和一些参数:
fig, ax = plt.subplots(tight_layout=True, figsize=(6, 6), subplot_kw=dict(projection='3d'))
plot = [ax.plot_surface(x, y, z[0], cmap=cm.Oranges, linewidth=0)]
ax.set_xlim(0, 31)
ax.set_ylim(0, 31)
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
ax.axis('off')
ax.plot([0, 0], [0, 31], [0, 0], c='black')
ax.plot([0, 31], [0, 0], [0, 0], c='black')
ax.plot([31, 0], [31, 31], [0, 0], c='black')
ax.plot([31, 31], [0, 31], [0, 0], c='black')
ax.view_init(50, 120)
绘制 3D 曲面动画并显示
ani = animation.FuncAnimation(
fig, update_map, 30, interval=100, fargs=(z, plot), repeat=True)
plt.show()
保存为gif
需要安装一下imagemagick
,谷歌/百度安装一下先。
ani.save('teaser' + '.gif', writer='imagemagick',fps=10)
完整代码
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import cm, rcParams
z = np.load('./data.npy')
x = np.linspace(0, 31, 32)
y = x
x, y = np.meshgrid(x, y)
fig, ax = plt.subplots(tight_layout=True, figsize=(6, 6), subplot_kw=dict(projection='3d'))
plot = [ax.plot_surface(x, y, z[0], cmap=cm.Oranges, linewidth=0)]
ax.set_xlim(0, 31)
ax.set_ylim(0, 31)
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
ax.axis('off')
ax.plot([0, 0], [0, 31], [0, 0], c='black')
ax.plot([0, 32], [0, 0], [0, 0], c='black')
ax.plot([31, 0], [31, 31], [0, 0], c='black')
ax.plot([31, 31], [0, 31], [0, 0], c='black')
ax.view_init(50, 120)
def update_map(num, z, plot):
plot[0].remove()
plot[0] = ax.plot_surface(x, y, z[num], cmap=cm.Oranges, linewidth=0)
ani = animation.FuncAnimation(
fig, update_map, 30, interval=100, fargs=(z, plot), repeat=True)
plt.show()
Reference
- https://pythonmatplotlibtips.blogspot.com/2018/11/animation-3d-surface-plot-funcanimation-matplotlib.html
- http://louistiao.me/posts/notebooks/save-matplotlib-animations-as-gifs/
下一篇: 浮点数的比较