|
|
使用 matplotlib.animation.FuncAnimation 对多个子图进行实时更新时,关键是在更新函数中同时处理两个坐标轴的数据更新和重绘。以下是为你的代码结构提供的解决方案:
- import matplotlib.pyplot as plt
- from matplotlib.animation import FuncAnimation
- import matplotlib.gridspec as gridspec
- import numpy as np
- # 创建图形和网格布局
- fig = plt.figure(figsize=(19.2, 10.8), dpi=100)
- fig.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.05)
- gs = gridspec.GridSpec(nrows=2, ncols=3)
- # 创建子图
- ax1 = fig.add_subplot(gs[0, 0]) # 多折线图
- ax2 = fig.add_subplot(gs[0, 1])
- ax3 = fig.add_subplot(gs[0, 2])
- ax4 = fig.add_subplot(gs[1, 0]) # 柱线组合图
- ax5_6 = fig.add_subplot(gs[1, 1:3])
- # 初始化数据存储
- lines1 = [] # 存储ax1的多条线对象
- bars = None # 存储ax4的柱状图对象
- line2 = None # 存储ax4的折线对象
- # 初始化ax1的多条折线(示例:3条线)
- for _ in range(3):
- line, = ax1.plot([], [], lw=2)
- lines1.append(line)
- # 初始化ax4的柱状图和折线
- x_data = np.arange(5) # 示例数据
- bars = ax4.bar(x_data, np.zeros_like(x_data), color='skyblue')
- line2, = ax4.plot([], [], 'r-', lw=2, marker='o')
- # 设置坐标轴范围
- ax1.set_xlim(0, 10)
- ax1.set_ylim(-1, 1)
- ax4.set_xlim(-0.5, 4.5)
- ax4.set_ylim(0, 10)
- def init():
- """初始化动画"""
- for line in lines1:
- line.set_data([], [])
- for bar in bars:
- bar.set_height(0)
- line2.set_data([], [])
- return lines1 + list(bars) + [line2]
- def update(frame):
- """更新函数,frame为当前帧数"""
- # 生成新数据(示例用随机数)
- new_x = np.linspace(0, 10, 100)
- for i, line in enumerate(lines1):
- new_y = np.sin(new_x + frame/10 + i) # 每条线相位不同
- line.set_data(new_x, new_y)
-
- # 更新柱状图数据
- new_bar_heights = np.random.rand(5) * 10
- for bar, h in zip(bars, new_bar_heights):
- bar.set_height(h)
-
- # 更新折线数据(示例:柱状图数据的累计和)
- new_line_y = np.cumsum(new_bar_heights)
- line2.set_data(x_data, new_line_y)
-
- # 自动调整纵坐标范围
- ax1.relim()
- ax1.autoscale_view()
- ax4.relim()
- ax4.autoscale_view()
-
- return lines1 + list(bars) + [line2]
- # 创建动画
- ani = FuncAnimation(
- fig, # 图形对象
- update, # 更新函数
- init_func=init, # 初始化函数
- frames=100, # 总帧数
- interval=100, # 更新间隔(ms)
- blit=True # 使用blitting优化
- )
- plt.show()
复制代码
关键要点:
1. 使用 init函数 初始化所有图形元素
2. 在 update函数 中同时更新两个子图的数据
3. 更新数据后调用 relim() 和 autoscale_view() 自动调整坐标轴范围
4. 设置 blit=True 可以提高渲染效率,但需要确保update函数返回所有被更新的图形对象
注意事项:
- 多折线图中每条线都需要单独存储和更新
- 柱线组合图中柱状图和折线图要分别更新
- 实际使用时将示例的随机数据替换为你的实时数据源
- 如果数据量很大,考虑使用 set_ydata() 而不是重新绘制
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|