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

Matplotlib动画colormesh时colorbar闪烁不一致问题求助

解决Matplotlib pcolormesh动画Colorbar闪烁问题

我尝试多种方法制作colormesh动画,最终选用FuncAnimation实现,代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

# 假设R、H、Nr、Nz、T、dt_real为已定义变量
r = np.linspace(0, R, Nr)
z = np.linspace(0, H, Nz)

fig, ax = plt.subplots()

# 初始化colormesh,固定vmin/vmax避免颜色范围波动
cax = ax.pcolormesh(r, z, T[0,:,:], cmap='RdBu_r', vmin=0, vmax=200)
ax.set_title("Variation of temperature with space")
ax.set_xlabel("r (m)")
ax.set_ylabel("z (m)")
fig.colorbar(cax)

def update(i):
    # 修正set_array调用:需通过cax调用,且传入展平后的数组
    cax.set_array(T[i,:,:].ravel())
    ax.set_title(f"Variation of temperature with space after a time of {i*dt_real} seconds")
    return cax,

ani = animation.FuncAnimation(fig, update, interval=100, frames=len(T)-1)
ani.save('123.gif')
plt.show()

数据说明

  • r、z:分别对应径向、轴向的坐标维度数组
  • T:三维矩阵,维度顺序为[时间步, z维度, r维度],目标是为每个时间步生成colormesh动画

问题现象

单独生成单张colormesh图完全正常,但生成的GIF动画中colorbar在帧间频繁闪烁、数值范围异常波动,无法复现逐帧渲染的正常效果。

解决方案

将动画输出格式从GIF改为MP4后,colorbar闪烁和异常问题完全消失。修改后的保存代码示例:

# 需提前安装ffmpeg编码器
ani.save('123.mp4', writer='ffmpeg')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:10:10