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

解决MatplotlibDeprecationWarning:缺失required_interactive_framework属性问题

解决Matplotlib 3.6+的FigureCanvas弃用警告问题

问题现象

运行Matplotlib绘图代码时,反复触发以下弃用警告:

MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later.
plt.plot(cache_sizes, hit_rates[i])

用户代码如下:

#!/usr/bin/env python3
import os
import subprocess

import matplotlib.pyplot as plt
import numpy as np

# cache_sizes = np.arange(0, 120, 20)
cache_sizes = np.arange(1, 5)
policies = ["FIFO", "LRU", "OPT", "UNOPT", "RAND", "CLOCK"]
# these were acheived after running `run.sh`
hit_rates = [
    # FIFO
    [45.03, 83.08, 93.53, 97.42],
    # LRU
    [45.03, 88.04, 95.20, 98.30],
    # OPT
    [45.03, 88.46, 96.35, 98.73],
    # UNOPT
    # NOTE: was unable to finish running this one, as it took too long.
    [45.03, None, None, None],
    # RAND
    [45.03, 82.06, 93.16, 97.36],
    # CLOCK
    [45.03, 83.59, 94.09, 97.73],
]

for i in range(len(policies)):
    plt.plot(cache_sizes, hit_rates[i])

plt.legend(policies)
plt.margins(0)
plt.xticks(cache_sizes, cache_sizes)
plt.xlabel("Cache Size (Blocks)")
plt.ylabel("Hit Rate")
plt.savefig("workload.png", dpi=227)

解决方法

方法1:明确指定Matplotlib后端

在导入pyplot前设置非交互式后端(如Agg),适配仅保存图片、无需交互的场景:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

方法2:更新Matplotlib到最新稳定版

该警告属于过渡性提示,后续版本已修复相关兼容性问题,执行以下命令更新:

pip install --upgrade matplotlib

方法3:临时过滤特定弃用警告

若不想修改代码或更新版本,可针对性屏蔽该警告:

import warnings
from matplotlib.cbook import MatplotlibDeprecationWarning

warnings.filterwarnings(
    "ignore",
    category=MatplotlibDeprecationWarning,
    message="Support for FigureCanvases without a required_interactive_framework attribute"
)

import matplotlib.pyplot as plt
import numpy as np

额外优化:处理None值避免绘图异常

代码中UNOPT的命中率包含None值,会导致绘图报错,建议过滤无效值后再绘图:

for i in range(len(policies)):
    # 过滤None值,匹配对应的缓存大小
    valid_indices = [idx for idx, val in enumerate(hit_rates[i]) if val is not None]
    valid_sizes = [cache_sizes[idx] for idx in valid_indices]
    valid_rates = [hit_rates[i][idx] for idx in valid_indices]
    plt.plot(valid_sizes, valid_rates)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:01:24