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

Jupyter Notebook中Matplotlib FuncAnimation动画轴刻度与标签模糊问题

Jupyter Notebook中Matplotlib FuncAnimation轴刻度与标签模糊问题解决方法

在Jupyter Notebook环境下使用Matplotlib的FuncAnimation生成并保存动画时,会出现轴刻度、标签模糊的情况,但在Python控制台运行同一代码则无此问题。复现该问题的最小代码如下:

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

x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots()

the_plot, = ax.plot([], [])  # Empty array for initialisation

ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(y), np.max(y))

def update(i):
    the_plot.set_data(x[:i+1], y[:i+1])

anim = animation.FuncAnimation(fig, update, range(len(x)), save_count=len(x))
anim.save('Out.mp4', fps=25, writer='ffmpeg')

以下是几种有效的解决方法:

  • 提高保存动画的DPI参数
    在anim.save()中显式指定高DPI值,提升视频分辨率,从根源上解决模糊问题:

    anim.save('Out.mp4', fps=25, writer='ffmpeg', dpi=300)
    
  • 设置全局绘图参数
    在代码开头添加全局配置,提升整体绘图的分辨率和字体尺寸,避免元素因缩放导致模糊:

    plt.rcParams['figure.dpi'] = 100
    plt.rcParams['savefig.dpi'] = 300
    plt.rcParams['font.size'] = 12
    
  • 切换Jupyter Notebook的Matplotlib后端
    在Notebook开头添加魔法命令,使用适配交互式环境的后端,优化渲染效果:

    %matplotlib notebook
    

    或使用静态渲染后端(适合仅需保存动画的场景):

    %matplotlib inline
    
  • 调整FFmpeg编码器参数
    通过指定更高的比特率优化视频画质,需要初始化FFMpegWriter并传入比特率参数:

    writer = animation.FFMpegWriter(fps=25, bitrate=1800)
    anim.save('Out.mp4', writer=writer)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:15:45