Seaborn绘图叠加问题咨询:修复方案与内存回收疑问
问题解答
一、修复方法
核心原因是Seaborn依赖的Matplotlib在长期运行的Web进程中,会复用全局的Figure实例,导致新图叠加在旧图上。可以通过以下两种方式解决:
1. 显式创建新Figure并在结束后关闭
在函数内手动创建新的Figure和Axes,绘图完成后关闭Figure释放资源:
import seaborn as sns import os import matplotlib.pyplot as plt from random import randint def make_histogram(data, filepath, destructive = True): sns.set() sns.set_style("whitegrid") sns.set_palette("husl") sns.set_context("paper") # 手动创建新的Figure和Axes fig, ax = plt.subplots() # 指定Axes绘图,避免复用全局实例 sns.histplot(data, ax=ax) if destructive and os.path.exists(filepath): os.remove(filepath) assert not os.path.exists(filepath) fig.savefig(filepath) # 关闭Figure,释放全局引用 plt.close(fig)
2. 使用上下文管理器自动清理
利用Matplotlib的上下文管理器,自动管理Figure的生命周期:
import seaborn as sns import os import matplotlib.pyplot as plt from random import randint def make_histogram(data, filepath, destructive = True): sns.set() sns.set_style("whitegrid") sns.set_palette("husl") sns.set_context("paper") # 上下文管理器会自动关闭Figure with plt.figure() as fig: sns.histplot(data) if destructive and os.path.exists(filepath): os.remove(filepath) assert not os.path.exists(filepath) fig.savefig(filepath)
二、为什么Figure未被垃圾回收
- 在FastAPI这类Web应用中,进程是长期运行的,Matplotlib的默认后端会将创建的Figure实例存储在全局的Figure管理器中,即使函数执行完毕,这些Figure仍然被全局变量引用,因此不会被Python的垃圾回收机制回收。
- 而Jupyter Notebook是交互式环境,每个单元格执行后会自动处理Figure的生命周期(比如自动显示并清理旧的Figure),所以不会出现复用问题。
内容的提问来源于stack exchange,提问作者Jred
相关产品推荐
相关产品推荐

