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

如何解决pandas.Series.plot()绘图时图像重叠问题?

解决pandas绘图时折线叠加的问题

问题根源是matplotlib默认会复用当前的绘图画布(figure),第一次循环生成的折线会保留在画布上,第二次绘图直接叠加,导致第二张图包含两条线。

以下两种简单修改方式都能解决问题:

方法1:每次循环创建新画布

导入matplotlib.pyplot,在每次绘图前新建空白画布,确保每次绘图独立:

import pandas as pd
import matplotlib.pyplot as plt

line1 = [1.23, 4.55, 6.72, 6.71]
line2 = [9.23, 7.52, 7.12, 9.71, 5.21]

data = [line1, line2]
for d in data:
    plt.figure()  # 新建空白画布
    data_series = pd.Series(d)
    result = data_series.plot(xlabel='Index', ylabel='Current', title=f'{d[0]}', grid=True, subplots=False)
    fig = result.get_figure()
    fig.savefig(f'{d[0]}.png')
    plt.close(fig)  # 可选:关闭画布释放内存

方法2:绘图后关闭当前画布

每次保存图片后关闭当前画布,避免后续绘图复用:

import pandas as pd
import matplotlib.pyplot as plt

line1 = [1.23, 4.55, 6.72, 6.71]
line2 = [9.23, 7.52, 7.12, 9.71, 5.21]

data = [line1, line2]
for d in data:
    data_series = pd.Series(d)
    result = data_series.plot(xlabel='Index', ylabel='Current', title=f'{d[0]}', grid=True, subplots=False)
    fig = result.get_figure()
    fig.savefig(f'{d[0]}.png')
    plt.close(fig)  # 关闭当前画布,下次绘图自动新建

两种方法都能保证每张图片只显示对应的数据折线,推荐第一种,逻辑更清晰,也能避免内存残留未关闭的画布。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:45:37