首页 > 解决方案 > Matplotlib - 将图形导出到内存缓冲区中的 png

问题描述

是否可以将 matplotlib 图形作为 png 导出为字节类型?这是我目前拥有的代码:

def import_chart(df, x_label, y_label, title):
    fig, ax = plt.subplots()
    ax.plot(data[x_label], data[y_label])

    ax.set(xlabel=x_label, ylabel=y_label,
           title=title)
    image_name = 'test.png'

    fig.savefig(image_name)
    f = open(image_name, 'rb+')
    img = f.read()
    f.close()
    os.remove(image_name)

    return img

返回的图像类型为“字节”类。我想避免保存到硬盘驱动器并再次读取它。像这样的东西:

def import_chart(self, x_label, y_label, title):
    fig, ax = plt.subplots()
    data = self.file_data.get_column([x_label,y_label])
    ax.plot(data[x_label], data[y_label])

    ax.set(xlabel=x_label, ylabel=y_label,
           title=title)
    buffer = buffer.to_buffer(fig.savefig(), format='png')
    img = buffer.read()
    return img

标签: pythonmatplotlibbuffer

解决方案


我一直在使用它从 Web 服务器渲染 matplotlib 图像:

import base64
from io import BytesIO

...

buffer = BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
image_png = buffer.getvalue()
buffer.close()
graphic = base64.b64encode(image_png)
graphic = graphic.decode('utf-8')

return graphic

推荐阅读