matplotlib将数字嵌入自动生成的html中

use*_*366 9 html python matplotlib

我想将python matplotlib生成的图形嵌入到具有其他内容的html文件中。那可能吗?

我想到的是将图形另存为png文件,然后使用<img>标记引用它。

我尝试使用的一些代码如下:

import matplotlib.pyplot as plt
fig = plt.figure()
#plot sth
plt.savefig('test.png')

html = 'Some html head' + '<img src=\'test.png\'>' + 'Some more html'

with open('test.html','w') as f:
    f.write(html)
Run Code Online (Sandbox Code Playgroud)

但是,这将生成两个文件,而不是一个,并且我没有服务器来托管png文件。可以将图形嵌入html吗?我如何在python中做到这一点。

谢谢。

Hao*_* Wu 13

您可以将图像写入临时文件并使用base64对其进行编码,然后将编码后的base64图像嵌入到html中。大多数现代浏览器将正确渲染图像。

从您的代码修改的一个简短示例将是:

import matplotlib.pyplot as plt
import base64
from io import BytesIO

fig = plt.figure()
#plot sth

tmpfile = BytesIO()
fig.savefig(tmpfile, format='png')
encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8')

html = 'Some html head' + '<img src=\'data:image/png;base64,{}\'>'.format(encoded) + 'Some more html'

with open('test.html','w') as f:
    f.write(html)
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,但是我发现我必须再做一个解码“编码”的步骤。`“ &lt;img src ='data:image / png; base64,{}'&gt;”。format(encoded.decode(“ utf-8”))` (3认同)
  • 我通过使用`encoded = base64.b64encode(tmpfile.getvalue())。decode('utf8')`&lt;img src ='data:image / png; base64,{{}}'&gt;`解决了我的问题。 (2认同)