python matplotlib.pyplot 绘制图表图像重叠的问题

def gen_graph(self, days): """ 根据历史数据绘制折线图并且保存 """ gas_list = self.get_histroy_gas(days) if gas_list: x = [] y = [] for index, gas in enumerate(gas_list): x.append(index+1) y.append(gas) # 计算变化百分比 percentage_change = [None] # 第一个点的变化百分比设为None for i in range(1, len(y)): change = ((y[i] - y[i - 1]) / y[i - 1]) * 100 percentage_change.append(change) # 生成折线图 plt.plot(x, y) plt.title(f'{len(gas_list)} days') plt.xlabel('day') plt.ylabel('GAS') # 在每个坐标点上显示Y轴的值和变化百分比 for i in range(len(x)): if percentage_change[i] is not None: plt.annotate(f'{y[i]} ({percentage_change[i]:.2f}%)', (x[i], y[i]), textcoords="offset points", xytext=(0, 10), ha='center') else: plt.annotate(f'{y[i]}', (x[i], y[i]), textcoords="offset points", xytext=(0, 10), ha='center') # 设置为整型 plt.xticks(x) # 保存折线图 plt.savefig(self.file_name) plt.close()
Enter fullscreen mode
Exit fullscreen mode
  • 上面这段代码中,如果plt.close()缺少这一行,绘制图将会一直缓存在内存在,对象不会被自动销毁,导致后面再绘制图形的时候,会和老的图像叠加;

  • 故,绘制图形一定要主动关闭,以此来主动清理内存


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Smart home network security. Jamb 2025 sure expo /sure jamb 2025 sure questions and answers assistance. Self management : a fundamental personal life skill for success and fulfillment.