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

我一直在使用它从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

最新更新