in

# 3 Methods to Embed a Matplotlib Chart into an HTML Web page | by Angelica Lo Duca | Jun, 2023

## A tutorial on the best way to import a Matplotlib chart into an HTML file

Python gives many libraries to carry out totally different operations, together with information visualization. Nonetheless, chances are you’ll discover integrating a chart constructed utilizing Matplotlib into an HTML web page complicated. The only resolution is to export the chart as a static picture, reminiscent of a PNG or JPEG, after which combine it into your HTML web page. Nonetheless, in the event you use a static picture, you lose any attainable interactivity from the unique chart.

One other resolution could possibly be utilizing exterior frameworks reminiscent of Streamlit or Flask, however in each circumstances, you need to arrange a standalone internet server to serve your picture. This resolution could possibly be too costly. In my city, we are saying we shoot a fly with a cannon!

This weblog submit reveals three methods to embed a Matplotlib chart into an HTML web page. The three options are:

• Utilizing the mpld3 library
• Encoding the picture as base64
• Utilizing `py-script`.

Earlier than describing every resolution, let’s describe the situation we’ll use to reveal the three circumstances.

Let’s suppose we wish to draw a sinusoid utilizing Matplotlib. Right here is the code to generate the chart:

`import numpy as npimport matplotlib.pyplot as plt# Generate x from 0 to 2*pi with a step dimension of 0.1x = np.arange(0, 2*np.pi, 0.1)y = np.sin(x)fig, ax = plt.subplots()ax.plot(x, y)ax.set_xlabel('x')ax.set_ylabel('y')ax.set_title('Sinusoid')plt.present()`

The next determine reveals the ensuing chart:

The mpld3 library combines Matplotlib and D3.js, a preferred Javascript library for information visualization. Mpld3 gives an API to export the Matplotlib charts in D3.js.

First, set up the mpld3 library:

`pip set up mpld3`

To save lots of your Matplotlib chart as an HTML web page, use the `save_html()` operate offered by mtpld3, as follows:

`import mpld3import numpy as npimport matplotlib.pyplot as plt# Generate x from 0 to 2*pi with a step dimension of 0.1x = np.arange(0, 2*np.pi, 0.1)y = np.sin(x)# Create a determine and axisfig, ax = plt.subplots()# Plot the sinusoidax.plot(x, y)# Set labels and titleax.set_xlabel('x')ax.set_ylabel('y')ax.set_title('Sinusoid')# Show the plotmpld3.save_html(fig,'fig.html')`

The `save_html()` operate receives a Matplotlib determine as an enter and the determine title. The script generates the `fig.html`. When you open it in your browser, you’ll see the next chart:

The chart is barely totally different from the unique one as a result of it’s the D3.js model of the unique chart. Which means the mpld3 library transforms the unique graph into D3.js. When you examine the HTML file out of your browser, you’ll see that the chart is an SVG picture, as proven within the following determine:

To embed the generated chart into one other HTML web page, copy the content material of the generated file exactly within the place the place you wish to embrace the picture. For extra particulars on the best way to proceed, comply with my previous tutorial.

One other resolution is encoding the Matplotlib determine as a base64 picture, as described on this Stack Overflow thread. Right here is the code to generate the HTML web page containing the Matplotlib picture:

`import base64from io import BytesIOimport numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 2*np.pi, 0.1)y = np.sin(x)fig, ax = plt.subplots()ax.plot(x, y)ax.set_xlabel('x')ax.set_ylabel('y')ax.set_title('Sinusoid')tmpfile = BytesIO()fig.savefig(tmpfile, format='png')encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8')html = '<html>' + '<img src='information:picture/png;base64,{}'>'.format(encoded) + '</html>'with open('fig2.html','w') as f:f.write(html)`

In observe you generate a `BytesIO()` object and save the determine utilizing the PNG format. Then use `b64encode()` operate to encode the picture and the `decode()` operate to decode it. Lastly, add the decoded picture to an HTML string and reserve it. Consequently, you have got exactly the unique Matplotlib determine.

Py-script is a Javascript library enabling you to incorporate Python code immediately into an HTML web page. To make use of Py-script, you need to embrace the next py-script library within the HTML heading:

`<head><hyperlink rel="stylesheet" href="https://pyscript.web/newest/pyscript.css" /><script defer src="https://pyscript.web/newest/pyscript.js"></script></head>`

Then, use the `py-config` tag to put in the required Python libraries:

`<py-config>packages = ["matplotlib", "numpy"]</py-config>`

Lastly, use the `py-scrip`t tag to incorporate your Python code:

` <py-script>import numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 2*np.pi, 0.1)y = np.sin(x)fig, ax = plt.subplots()ax.plot(x, y)ax.set_xlabel('x')ax.set_ylabel('y')ax.set_title('Sinusoid')show(fig, goal="graph-area", append=False)</py-script><div id="graph-area"></div>`

To indicate the determine, use the `show()` operate, which receives the Matplotlib determine, the HTML `div` the place to incorporate the plot and if to make use of the `append` modality.

As a remaining outcome, you have got exactly the identical determine as the unique one.

Congratulations! You may have simply discovered 3 ways to incorporate a Matplotlib chart into an HTML web page! The three methods are:

• Utilizing the mpld3 library converts your Matplotlib chart right into a D3.js chart
• Encoding the picture as base64 generates a PNG picture of the Matplotlib chart as a base64 encoded picture after which consists of it into an HTML web page
• Utilizing `py-script` allows you to embrace your Python code immediately in HTML.