Is it possible to use custom plotly.offline.iplot_mpl code in Dash

I have alot of custom code in matplotlib and currently use plotly.offline.iplot_mpl to make graphs interactive in a Jupyter notebook (see Figure below). Is it possible to do the same within a Dash app?

You can’t really use plotly.offline.iplot_mpl as this doesn’t return the figure object needed by the dcc.Graph object.
Instead, you can use plotly.tools.mpl_to_plotly e.g.

from plotly.tools import mpl_to_plotly
import dash_core_components as dcc

plotly_fig = mpl_to_plotly(mpl_fig)
graph = dcc.Graph(id='myGraph', fig=plotly_fig)

where mpl_fig is a matplotlib figure object.

1 Like

Thanks @mikesmith1611. This worked perfectly!

2 Likes

Hi all,

I just wanted to post a complete example hoping it would be helpful for people like me trying to render matplotlib graphs using plotly:

from plotly.tools import mpl_to_plotly
from matplotlib import pyplot as plt
import dash
import dash_html_components as html
import dash_core_components as dcc

app= dash.Dash()

fig= plt.figure()
ax= fig.add_subplot(111)
ax.plot(range(10), [i**2 for i in range(10)])
ax.grid(True)
plotly_fig = mpl_to_plotly(fig)

app.layout= html.Div([
    dcc.Graph(id= 'matplotlib-graph', figure=plotly_fig)

])

app.run_server(debug=True, port=8010, host='localhost')

I got the hint from this post but took me really long to figure out the proper way. :slight_smile:

1 Like

Just discovered that mpl_to_plotly no longer works with the current version of matplotlib, and is considered to be deprecated.

And what should we do instead? Is there a new method available?