matplotlib将数字嵌入自动生成的html中 [英] matplotlib embed figures in auto generated html

查看:103
本文介绍了matplotlib将数字嵌入自动生成的html中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to embed a figure generated by python matplotlib into a html file with other content. Is that possible?

我认为是将图形另存为png文件,然后使用< img> 标记来引用它.

What I have thought is saving figures as png file and then use <img> tag to refer to it.

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

Some code I was trying to use are like:

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中做到这一点.

However, this will generate two files instead of one and I don't have a server to host the png file. Is that possible to embed the figure in the html? How do I do it in python.

谢谢.

推荐答案

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

You can write the image into a temporary file and encode it with base64 and then embed the encoded base64 image into your html. Most modern browsers will correctly render the image.

根据您的代码修改而成的简短示例为:

A short example modified from your code will be:

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)

这篇关于matplotlib将数字嵌入自动生成的html中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆