目录
Python各类图形绘制—Matplotlib库-动态图形绘-旋转方形
前言
开发环境
Matplotlib_demo
动态Matplotlib绘制注意内容
旋转过程中改变颜色
Matplotlib在动态图形绘制中的优势
高度的灵活性
与 Python 的良好集成
动画制作能力
输出格式丰富
既然是学习数学,肯定会离不开各种图形,之前的文章中很多我都尽可能的不使用图来表示了,但是觉得不好,毕竟数学离开了图就会很抽象,所以我们这里单独的学习一下Python的各类图形绘制,包含绘制切线什么的,这样在数学学习的图像处理上就会好很多。
图形 | 动态效果 | 展示方式 |
正方形 | 旋转 | gif |
系统:win11
开发语言:Python
使用工具:Jupyter Notebook
使用库:Matplotlib
代码示例:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.patches as patches
# 设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 创建图形和轴
fig, ax = plt.subplots(figsize=(8, 8))
# 设置坐标轴范围
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
# 创建方块
square = patches.Rectangle((-0.5, -0.5), 1, 1,
facecolor='#00A0E9', # 蓝色
edgecolor='none')
ax.add_patch(square)
# 定义动画更新函数
def update(frame):
# 每帧旋转45度
square.set_angle(frame * 45)
return square,
# 创建动画
anim = FuncAnimation(fig, update,
frames=8, # 8帧完成一次旋转
interval=500, # 每帧间隔500毫秒
blit=True,
repeat=True) # 循环播放
# 设置坐标轴
ax.set_aspect('equal')
ax.grid(True, linestyle='--', alpha=0.3)
ax.set_title('旋转方块动画')
# 保存为GIF
anim.save('./rotating_square.gif',
writer='pillow', fps=2)
plt.show()
效果示例:
FuncAnimation类的正确使用
frames参数设置合适的帧数
interval控制帧间隔时间
blit=True启用优化
代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.patches as patches
# 设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 创建图形和轴
fig, ax = plt.subplots(figsize=(8, 8))
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
# 定义颜色列表
colors = ['#00A0E9', '#FF6B6B', '#4ECB71', '#FFB400',
'#9B59B6', '#3498DB', '#E74C3C', '#2ECC71']
# 创建方块
square = patches.Rectangle((-0.5, -0.5), 1, 1,
facecolor=colors[0],
edgecolor='none')
ax.add_patch(square)
# 定义动画更新函数
def update(frame):
# 更新旋转角度和颜色
square.set_angle(frame * 45)
square.set_facecolor(colors[frame % len(colors)])
return square,
# 创建动画
anim = FuncAnimation(fig, update,
frames=8,
interval=500,
blit=True,
repeat=True)
# 设置坐标轴
ax.set_aspect('equal')
ax.grid(True, linestyle='--', alpha=0.3)
ax.set_title('旋转变色方块动画')
# 保存为GIF
anim.save('./rotating_color_square.gif',
writer='pillow', fps=2)
plt.show()
实际效果:
可以看到选中中颜色一直是变化的。
animation
模块,其中包含了简洁而强大的 API,用于创建各种类型的动画。通过定义帧函数和更新函数,用户可以轻松地实现图形元素的动态变化,如移动、缩放、旋转等,从而制作出流畅的动态图形。