Home > other >  python how to iteratively export plots and text to html
python how to iteratively export plots and text to html

Time:03-04

I have a loop to create matplotlib figures:

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)

It all presented nicely in my nb but how want to export it to an HTML with all the text and the images. What is the based way to do so?

CodePudding user response:

You can define a function to convert the figures to 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}\'>'

Example with your data:

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)

output:

<html>
<p>0</p>
<img src='data:image/png;base64,iVBORw0KGg...'>
<p>1</p>
<img src='data:image/png;base64,iVBORw0KGg...'>
</html>
  • Related