实现思路
- html可以以base64代码的形式内嵌图片。具体形式为 <img src="data:image/png; base64, iVBORw...。后面的 iVBORw…即为图像的 Base64 编码信息。故而只需将图像转为 base64 代码即可将图像嵌入 HTML 代码字符串中。
- matplotlib 的 pyplot.savefig() 函数可以将绘图窗口保存为二进制文件格式。
- lxml 库的 etree 模块可以实现解析 HTML 代码并写入 html 文件
代码实现
import matplotlib.pyplot as plt
from io import BytesIO
from lxml import etree
import base64
import webbrowser
plt.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
x = range(10) # 横轴的数据
y = [i*i for i in x] # 纵轴的数据
y1 = [i*i+123 for i in x] # 纵轴的数据
plt.title('Demo')
plt.plot(x, y, '1m:', label=u'compare') # 加上label参数添加图例
plt.plot(x, y1, '>r--', label=u'set other') # 加上label参数添加图例
plt.xlabel(u"横轴的数据")
plt.ylabel(u"纵轴的数据")
plt.legend() # 让图例生效
# figure 保存为二进制文件
buffer = BytesIO()
plt.savefig(buffer)
plot_data = buffer.getvalue()
#plt.show() # 显示绘制出的图
# 图像数据转化为 HTML 格式
imb = base64.b64encode(plot_data)
ims = imb.decode()
imd = "data:image/png;base64,"+ims
test_im = """<h1>Demo Figure</h1> """ + """<img src="%s">""" % imd
# lxml 库的 etree 解析字符串为 html 代码,并写入文件
html = etree.HTML(test_im)
tree = etree.ElementTree(html)
tree.write('demo.html')
# 最后使用默认浏览器打开 html 文件
webbrowser.open('demo.html', new=1)