【问题标题】:matplotlib embed figures in auto generated html [duplicate]matplotlib在自动生成的html中嵌入数字[重复]
【发布时间】:2023-04-11 01:56:01
【问题描述】:

我想将 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)

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

谢谢。

【问题讨论】:

标签: python html matplotlib


【解决方案1】:

您可以使用 base64 编码转换图像: https://docs.python.org/3/library/base64.html#base64.encodebytes

然后将编码后的字符串嵌入到 html 中,如下所示: How to display Base64 images in HTML?

【讨论】:

    【解决方案2】:

    您可以将图像写入临时文件并使用 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)
    

    【讨论】:

    • 这对我有用,但我发现我必须执行额外的步骤来解码encoded。 "&lt;img src='data:image/png;base64,{}'&gt;".format(encoded.decode("utf-8"))
    • 我通过使用encoded = base64.b64encode(tmpfile.getvalue()).decode('utf8') &lt;img src='data:image/png;base64,{{}}'&gt;解决了我的问题
    • 很棒的答案! ?????
    猜你喜欢
    • 2012-02-21
    • 2011-07-12
    • 2018-11-30
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多