python - 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
推荐阅读
- c# - 无法将 ASP.NET Core 2.1 Angular 应用程序部署到 Azure
- ajax - Laravel 动态依赖下拉菜单
- javascript - 更新或将对象推送到找到的文档 mongoose 中的嵌套数组中
- javascript - 检查可变颜色
- python - Pandas 添加索引以对列求和
- github - 将 markdown 表文件嵌入到 github wiki
- google-analytics - 为什么用户快照不能在谷歌分析中显示事件日志?带有 gtm 的网站
- python - matplotlib.image 运行时出现“找不到文件”错误
- python - 当函数只能返回 str 时,mypy 抱怨返回值类型不兼容(得到“可选 [str]”,预期为“str”)
- python - 我有 Python 3.8 的站点包,但没有解释器