Search code examples
htmlcsspython-3.xmatplotlibmpld3

Output a centred HTML image with mpld3


I am using the mpld3 Python package to save out static matplotlib figures as interactive images in the html format. A quick example is the following:

# draw a static matplotlib figure
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x))

# save as an interactive html file
import mpld3

html_str = mpld3.fig_to_html(fig)
Html_file= open("sample.html","w")
Html_file.write(html_str)
Html_file.close()

But the problem is that when opening the html image in a browser, it is always on the top-left. Is there a way to make it center or even have more control of the output style?

screenshot


Solution

  • mpld3.fig_to_html() just generates a piece of fragment of html. Though the fragment alone can work as an html document, it is supposed to be embedded into a full html document.

    Below is an example of the solution specifying id fig1 to the generated fragment using figid option. Preparing html document with CSS style definition for <div> having id fig1. And embed the fragment into the document.

    html_fragment = mpld3.fig_to_html(fig, figid = 'fig1')
    
    html_doc = f'''
    <style type="text/css">
    div#fig1 {{ text-align: center }}
    </style>
    
    {html_fragment}
    '''
    
    Html_file= open("sample.html","w")
    Html_file.write(html_doc)
    Html_file.close()