dash show static plot figure

Dash can show matplotlib as static image as well.

THis is basically using the static html tag, referenced through html.Img.

This is not through the dcc graph requires a numpy array input can visualize through javascript.

The key thing here is to save the plot into bytes buffer and encode the bytes stream into utf-8, and then use it as the image source.


from dash import Dash, html

from io import BytesIO

import base64

import matplotlib.pyplot as plt


dash_app = Dash(__name__)

app = dash_app.server



fig = plt.figure()

plt.plot([1,2,3],[3,4,5])

fig_buffer = BytesIO()

plt.savefig(fig_buffer, format='png')    

encoded = base64.b64encode(fig_buffer.getvalue()).decode("utf-8")

fig_src = "data:image/png;base64, " + encoded


dash_app.layout = html.Div([html.Img(id="static_heatmap",className="image", src = fig_src)])


if __name__ == '__main__':

    dash_app.run_server()