DEV Community

drake
drake

Posted on

1 1 1 1 1

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()缺少这一行,绘制图将会一直缓存在内存在,对象不会被自动销毁,导致后面再绘制图形的时候,会和老的图像叠加;

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay