为什么在生成pdf时在reportlab中出现“内存错误”

时间:2019-08-29 12:16:20

标签: python pandas matplotlib pdf reportlab

我一直在尝试使用reportlab生成pdf。 当我放4张图片时,它可以工作。 但是我只放了5张图像,显示内存错误。 请帮忙。

代码如下:

def plot_graph():
    plt.figure(figsize=(8, 5.25))

    stats = data.resample('D', on='DATE').count()['DATE']
    stats.plot(figsize=(12, 12))
    plt.xlabel('Dates', fontsize=16)
    plt.ylabel('Number of People', fontsize=16)
    plt.grid()

    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=300)
    buf.seek(0)

    return buf




def plot_graph1():
    plt.figure(figsize=(8, 5.25))

    stats = data.resample('D', on='DATE').count()['DATE']
    stats.plot(figsize=(12, 12))
    plt.xlabel('Dates', fontsize=16)
    plt.ylabel('Number of People', fontsize=16)
    plt.grid()

    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=300)
    buf.seek(0)

    return buf1

与情节2、3、4类似。这样总共有5个地块。

image_buffer1 = plot_graph()
im = Image(image_buffer1, 8 * inch, 5.25 * inch)
Story.append(im)

add_text("Description of the chart.")

image_buffer1 = plot_graph1()
im2 = Image(image_buffer2, 8 * inch, 5.25 * inch)
Story.append(im2)

add_text("Description of the chart.")

与情节2、3、4类似。这样总共有5个地块。

请帮助。 我的代码有什么问题?

错误:

 name = _digester(rawdata+mdata)
MemoryError

1 个答案:

答案 0 :(得分:1)

您内存不足的最可能原因是因为您没有关闭plt

我使用此功能在PDF中保存并绘制绘图:

def save_and_draw(fig, x_img, y_img, width_img=width_img, height_img=height_img):

    imgdata = BytesIO()
    fig.savefig(imgdata, format="png")
    imgdata.seek(0)
    imgdata = ImageReader(imgdata)

    self.c.drawImage(imgdata, x_img, y_img, width_img, height_img)
    plt.close(fig)

其中一些拥有15个以上的地块,一切对我来说都很好。希望对您有帮助!