【问题标题】:Is there a way to save a Seaborn or matplotlib plot as an html string/object?有没有办法将 Seaborn 或 matplotlib 图保存为 html 字符串/对象?
【发布时间】:2022-12-10 17:40:05
【问题描述】:
有没有一种方法可以让我将 seaborn 或 matplotlib 图表保存为 html 字符串?我正在尝试将多个(大约 20 个)图表嵌入到每天通过电子邮件发送的自动报告中。我报告的其他方面以 html 为基础。只是想确认我必须依赖来自 seaborn/matplotlib 的仅图像对象。
我 orgianlly 使用 altair 并将 json 嵌入到我的电子邮件中,但是这无法在任何电子邮件应用程序中呈现,因为大多数电子邮件应用程序都禁用了 javascript/css。
【问题讨论】:
标签:
python
pandas
matplotlib
seaborn
【解决方案1】:
HTML 允许您显示使用 base64 编码的任何图像,请考虑以下小红点示例
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
取自How to Display Base64 Images in HTML。在您的情况下,您需要:使用 seaborn 生成的 base64 编码的 PNG 图像,您可以使用 base64 进行以下操作
import base64
import seaborn as sns
fig = sns.heatmap([[1,2],[3,4]]).get_figure()
fig.savefig('heatmap.png')
with open('heatmap.png','rb') as f:
b64data = base64.b64encode(f.read()) # b64data is bytes, use b64data.decode() if you need str