python 如何将绘图和文本迭代导出到 html
python how to iteratively export plots and text to html
我有一个循环来创建 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)
它在我的笔记本电脑中呈现得很好,但如何将其导出到包含所有文本和图像的 HTML。
这样做的基础方法是什么?
您可以定义一个函数将数字转换为 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>
我有一个循环来创建 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)
它在我的笔记本电脑中呈现得很好,但如何将其导出到包含所有文本和图像的 HTML。 这样做的基础方法是什么?
您可以定义一个函数将数字转换为 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>