Showing a simple matplotlib plot in plotly Dash

UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail

in my case it works, despite the warning message 👍👍


If you don't want an interactive plot, you can return a static one (found from this help)

import io
import base64

...

app.layout = html.Div(children=[
    ...,

    html.Img(id='example') # img element
])

@app.callback(
    dash.dependencies.Output('example', 'src'), # src attribute
    [dash.dependencies.Input('n_points', 'value')]
)
def update_figure(n_points):
    #create some matplotlib graph
    x = np.random.rand(n_points)
    y = np.random.rand(n_points)
    buf = io.BytesIO() # in-memory files
    plt.scatter(x, y)
    plt.savefig(buf, format = "png") # save to the above file object
    plt.close()
    data = base64.b64encode(buf.getbuffer()).decode("utf8") # encode to html elements
    return "data:image/png;base64,{}".format(data)

Refer to https://plot.ly/matplotlib/modifying-a-matplotlib-figure/ . There is a mpl_to_plotly function in plotly.tools library that will return a plotly figure(which can then be returned to Graph's figure attribute) from matplotlib figure.

Edit: Just noticed you asked this a while back. Maybe the above is a new feature but its the cleanest way.