Search code examples
pythonflaskseabornmpld3

Saving graphs to .html using mpld3


I am trying to show a graph using seaborn and mpld3 but in a .html file. When I use the command mpld3.show(), a new window pops and the graph is shown in a local webserver created (like the documentation describes). However, when trying to save it in a .html file, the graph comes empty but I can see some icons like move and zoom avaliable....

With mpld3.show()

sns.set(style="whitegrid")
sns.barplot(x=df.index.tolist(), y=df['Salário'])
mpld3.show()

Graph how its supposed to be:

Trying to save to .html file using save_html():

sns.set(style="whitegrid")
sns.barplot(x=df.index.tolist(), y=df['Salário'])
fig = plt.figure()
mpld3.save_html(fig, "./templates/graph_exp.html")

Bugged graph with working icons

Can someone help me make this graph appear normal saving to a .html file? :)


Solution

  • I am not sure how save_html() works but this is what i use on my flask website.

    This solution works if you do not need to save the image.

    import base64
    import io
    
    
    pngImage = io.BytesIO()
    FigureCanvas(fig).print_png(pngImage) #fig is my matPlotlib instance of Figure()
    
    # Encode PNG image to base64 string
    image = "data:image/png;base64,"
    image += base64.b64encode(pngImage.getvalue()).decode('utf8')
    

    then in html use:

    <img src="{{image}}">