【发布时间】:2020-05-07 15:50:44
【问题描述】:
是否可以将 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
【问题讨论】:
标签: python matplotlib buffer