如何解决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
相关产品推荐
相关产品推荐

