如何用Python的Plotly结合Frames和Slider绘制双热力图?
实现带滑块动画的并排双热力图(Plotly)
以下是完整的可运行解决方案,完美结合静态双热力图布局与滑块动画功能:
import plotly.graph_objects as go from plotly.subplots import make_subplots import numpy as np # 数据加载(替换为你的文件路径) files = { 'gas': np.load('gas.npy'), 'solid': np.load('solid.npy') } # 校验两组数据帧数一致 assert len(files['gas']) == len(files['solid']), "gas和solid数据帧数必须匹配" num_frames = len(files['gas']) # 计算全局颜色范围(保证动画过程中颜色刻度稳定) gas_min, gas_max = np.min(files['gas']), np.max(files['gas']) solid_min, solid_max = np.min(files['solid']), np.max(files['solid']) # 1. 创建基础子图布局(复用静态图的配置) fig = make_subplots(rows=1, cols=2, shared_yaxes=True, shared_xaxes=True) # 2. 添加初始帧的两个热力图 fig.add_trace( go.Heatmap(z=files['gas'][0].T, coloraxis='coloraxis1', zmin=gas_min, zmax=gas_max), row=1, col=1 ) fig.add_trace( go.Heatmap(z=files['solid'][0].T, coloraxis='coloraxis2', zmin=solid_min, zmax=solid_max), row=1, col=2 ) # 3. 构建动画Frames:每个Frame包含当前帧的双热力图数据 frames = [] for i in range(num_frames): frame = go.Frame( data=[ # 左子图:gas当前帧 go.Heatmap(z=files['gas'][i].T, coloraxis='coloraxis1', zmin=gas_min, zmax=gas_max), # 右子图:solid当前帧 go.Heatmap(z=files['solid'][i].T, coloraxis='coloraxis2', zmin=solid_min, zmax=solid_max) ], name=str(i) ) frames.append(frame) # 4. 配置滑块、播放按钮与整体布局 fig.update(frames=frames) fig.update_layout( # 静态图原有布局配置 legend=dict(x=0.5, xanchor='center', y=1, yanchor='bottom', orientation='h'), coloraxis1=dict(colorscale='jet', colorbar_x=-0.20, colorbar_thickness=10), coloraxis2=dict(colorscale='jet', colorbar_x=1.00, colorbar_thickness=10), width=800, height=700, yaxis={"title": 'y [m/10]'}, xaxis={"title": 'r [m/10]', 'side': 'top'}, xaxis2={"title": 'r [m/10]', 'side': 'top'}, title_x=0.5, # 滑块配置 sliders=[{ "steps": [ { "args": [[f.name], {"frame": {"duration": 300, "redraw": True}, "mode": "immediate"}], "label": str(f.name), "method": "animate" } for f in frames ], "currentvalue": {"prefix": "Frame: "} }], # 播放/暂停按钮 updatemenus=[{ "type": "buttons", "buttons": [ {"label": "Play", "method": "animate", "args": [None, {"frame": {"duration": 300}, "fromcurrent": True}]}, {"label": "Pause", "method": "animate", "args": [[None], {"frame": {"duration": 0}, "mode": "immediate"}]} ], "x": 0.5, "xanchor": "center", "y": -0.15 }] ) fig.show()
核心实现要点
- 双Trace帧结构:每个动画Frame必须包含两个热力图对象,分别对应左右子图的当前帧数据,这是实现同步更新的核心。
- 稳定颜色刻度:提前计算每组数据的全局最小/最大值并绑定到热力图,避免动画切换时颜色范围跳变,保证可视化一致性。
- 子图布局复用:完全继承静态图的子图配置(共享轴、独立颜色轴),确保布局与静态图完全一致。
- 滑块绑定逻辑:每个滑块步骤与Frame一一对应,通过
mode: immediate实现即时视图更新。
内容的提问来源于stack exchange,提问作者Lucas Quaresma
相关产品推荐
相关产品推荐

