我有一個回圈來創建 matplotlib 數字:
x1 = np.array([1,2,3,4,5])
x2 = np.array([1,3,3,8,5])
x3 = np.array([9,2,5,4,5])
n = 30
for i in n:
print(f"============{i}==========")
fig, axs = plt.subplots(1, 3, figsize=[18, 10])
axs[0].plot(x1)
axs[1].plot(x2)
ax2[2].plot(x3)
這一切都在我的 nb 中很好地呈現,但如何將其匯出為包含所有文本和影像的 HTML。這樣做的基礎方法是什么?
uj5u.com熱心網友回復:
您可以定義一個函式將數字轉換為 base64:
def fig2html(fig):
import base64, io
b = io.BytesIO()
fig.savefig(b, format='png')
b64 = base64.b64encode(b.getvalue()).decode('utf-8')
return f'<img src=\'data:image/png;base64,{b64}\'>'
您的資料示例:
x1 = np.array([1,2,3,4,5])
x2 = np.array([1,3,3,8,5])
x3 = np.array([9,2,5,4,5])
n = 2
html_data = []
for i in range(n):
html_data.append(f'<p>{i}</p>')
fig, axs = plt.subplots(1, 3, figsize=[3, 2])
axs[0].plot(x1)
axs[1].plot(x2)
axs[2].plot(x3)
html_data.append(fig2html(fig))
simple_template = '<html>\n%s\n</html>'
html = simple_template % '\n'.join(html_data)
輸出:
<html>
<p>0</p>
<img src='data:image/png;base64,iVBORw0KGg...'>
<p>1</p>
<img src='data:image/png;base64,iVBORw0KGg...'>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/437724.html
標籤:Python html 图片 matplotlib
