Python matplotlib 批量绘图内存不够

发布于 2022-08-18  807 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

问题描述: Python绘图批量绘图时如果每张图片都显示会出现“out of memory"内存不够或者最多只能显示20张图的报错

解决方案1:

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

>注意导入顺序,缺一不可。
matplotlib.use(‘agg’):作用是matplotlib设定为非交互式,前端不会展示绘图结果

example:

import numpy as np
import random
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

for i in range(10):
    #1. Generate data array
    x = np.random.normal(0, 1, 10)
    y = np.random.normal(0, 1, 10)
    #2.画布设置:
    plt.figure(figsize=(10, 10), dpi=80)
    ax=plt.subplot2grid((1,1), (0,0), facecolor='w')
    #3.绘制散点图或折线图
    plt.scatter(x,y, c='pink', s=5)    
    #4.保存图片
    plt.savefig('C:\Users\AQ84510'+str(i)+'.jpg')
    plt.clf()
    plt.close()

解决方案2

画完图保存之后直接加上
plt.close(fig)

import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
x=[0,1,2]
y=[3,4,5]
ax.plot(x,y )
fig.savefig('path/picture.png') # save the figure to file folder
plt.close(fig) # close the figure

解决方案3

循环外部创建fig对象并循环使用,使用plt.clf()清理axes

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(5,4)) # 在循环外部创建一个fig对象,循环利用
for i in range(10000):
    print('figure %d' % i)
    x=[1,2,3]
    y=[4,5,6]
    plt.plot(x, y, 'k', linewidth=0.2)
    plt.axis('off')
    # 去除边框
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
    plt.margins(0,0)
    filesave = 'D:\\'+str(i)+'.png'
    fig.savefig(filesave, format='png', transparent=True, dpi=200, pad_inches = 0) # 选择合适的分辨率
    plt.clf() # 使用 plt.clf() 清理掉 axes
Everything not saved will be lost.
最后更新于 2022-08-18