How to embed matplotlib figure in html

Sometime, when we use third-party tool, which may provide visualization using matplotlib to plot figure and visualize the results. It is ok if we only use this tool. However, if we want to integrate these figures with other tools. The figures cannot be used. For example, I use backtrader to do backtest and visualize the signal and buy/sell datetime (figure plot), while using quantstats to do capitabl & gain/loss analysis (can view in html). It is better to merge them into one html to do visulization.

Because image is easily embedded in html using base64 coding, I convert plot figure into image base64. The following code snippet do the coversion

def figure2base64(fg):
    img = None
    with BytesIO() as img_buf:
        plt.savefig(img_buf, format='jpg')
        img = base64.b64encode(img_buf.getbuffer()).decode('utf-8')
    
    return img

The input is a figure instance, which can be plot.show() to display, and the return is base64 encoded image, which can be embedded into html using the following

<img src="data:image/jpeg;base64,base64_image />

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s