You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib双动画子图实现:如何同时更新两个子图

同步更新Matplotlib双生子图动画(网络图+折线图)

核心修改思路

要实现两个子图的同步动画,关键是在同一个update函数内完成两个子图的更新逻辑,并将所有需要动态刷新的绘图对象返回给FuncAnimation。具体步骤如下:

  1. 初始化折线图元素:提前创建时间轴数据、两条折线对象,保存引用以便后续更新。
  2. 扩展update函数:在原有网络图更新逻辑后,添加折线图的数据更新代码,同时更新折线图标题显示当前时间步。
  3. 收集所有更新对象:将网络图的边对象、折线图的线条对象、更新后的标题都加入返回的艺术家列表,确保blit=True模式下能正确刷新。

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation
from netgraph import Graph

# Simulate a dynamic network with
total_frames = 21
total_nodes = 5
NODE_LABELS = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
NODE_POS = {0: (0.0, 0.5), 1: (0.65, 0.25), 2: (0.7, 0.5), 3: (0.5, 0.75), 4: (0.25, 0.25)}
adjacency_matrix = np.random.rand(total_nodes, total_nodes) < 0.25
weight_matrix = np.random.randn(total_frames, total_nodes, total_nodes)

# Normalise the weights, such that they are on the interval [0, 1].
vmin, vmax = -2, 2
weight_matrix[weight_matrix<vmin] = vmin
weight_matrix[weight_matrix>vmax] = vmax
weight_matrix -= vmin
weight_matrix /= vmax - vmin

cmap = plt.cm.RdGy

def annotate_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure(figsize=(11, 6))

ax1 = plt.subplot2grid((6, 11), (0, 0), rowspan=6, colspan=5)
ax2 = plt.subplot2grid((6, 11), (1, 6), rowspan=2, colspan=5)

annotate_axes(fig)
title1 = ax1.set_title('Simulation viz', x=0.25, y=1.25)
# 初始化折线图标题,后续动态更新
title2 = ax2.set_title('Flow @t=0', x=0.15, y=1.25)

g = Graph(adjacency_matrix, node_labels=NODE_LABELS,
            node_layout = NODE_POS, edge_cmap=cmap, arrows=True, ax=ax1)

# -------------------------- 新增折线图初始化代码 --------------------------
# 生成时间步数据,对应total_frames帧
x_data = np.arange(total_frames)
# 初始化两条折线的y数据(初始为0,后续逐帧更新)
y_sin = np.zeros(total_frames)
y_cos = np.zeros(total_frames)

# 创建折线对象,保存引用以便更新(注意逗号,确保获取单个Line2D对象)
line_sin, = ax2.plot(x_data, y_sin, label='sin(t)')
line_cos, = ax2.plot(x_data, y_cos, label='cos(t)')
ax2.legend()
# 打开坐标轴标签(按需调整)
ax2.tick_params(labelbottom=True, labelleft=True)
ax2.set_xlabel('Time Step')
ax2.set_ylabel('Value')
# 设置固定y轴范围,避免动画过程中坐标轴跳动
ax2.set_ylim(-1.2, 1.2)
# -------------------------------------------------------------------------

def update(ii):
    artists = []
    # 更新网络图部分(原有逻辑)
    for jj, kk in zip(*np.where(adjacency_matrix)):
        w = weight_matrix[ii, jj, kk]
        artist = g.edge_artists[(jj, kk)]
        artist.set_facecolor(cmap(w))
        artist.update_width(0.03 * np.abs(w-0.5))
        artists.append(artist)
    
    # -------------------------- 新增折线图更新代码 --------------------------
    # 更新到当前帧的sin和cos数据
    y_sin[:ii+1] = np.sin(x_data[:ii+1] * np.pi / 10)
    y_cos[:ii+1] = np.cos(x_data[:ii+1] * np.pi / 10)
    
    # 更新折线数据
    line_sin.set_ydata(y_sin)
    line_cos.set_ydata(y_cos)
    
    # 更新折线图标题
    title2.set_text(f'Flow @t={ii}')
    
    # 将折线和标题加入更新列表
    artists.extend([line_sin, line_cos, title2])
    # -------------------------------------------------------------------------
    
    return artists

animation = FuncAnimation(fig, update, frames=total_frames, interval=200, blit=True, repeat=False)
plt.show()

细节说明

  • 折线图初始化时设置固定y轴范围,避免动画过程中坐标轴频繁缩放导致画面跳动。
  • 使用line_sin, = ax2.plot(...)的写法(注意逗号),确保获取单个Line2D对象,方便后续调用set_ydata更新数据。
  • blit=True模式下,所有动态变化的元素(网络图的边、折线、标题)都必须加入返回的artists列表,否则这些元素不会被刷新。

内容的提问来源于stack exchange,提问作者carpediem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 06:37:34