Black Lives Matter. Please consider donating to Black Girls Code today.

Best way to incorporate matplotlib plot in Dash App

Hey general question: I want to incorporate a matplotlib figure (which will be updated during runtime depending on user input) into my plot and found a few options:

-make it an image, add as html.Img as seen here

-convert it to a plotly figure using mpl_to_plotly (which somehow didnt really work, especially passing new ones to the graph after one sat there initially lead to some kind of async handler issue and the dash process stopped altogether)

As a general concept, what would be the easiest and hopefully most efficient way to do it? Can I just return a plotly Figure to the Dash Graph objects figure attribute?

EDIT: Main issue is btw that it doesnt seem to update properly, meaning the Image is static after first callback.

This is the recommended way to do this.

Can you share a small, reproducable example?

1 Like

I’ll share my solution if I find one. It’s kinda hard to reproduce a small sample, because it builds on a rather complex structure. The matplotlib figure e.g. is delivered by a custom plotting library used in our research group. Right now Tkinter also throws a few not so nice threading errors. Maybe my callback is also messed up. I’ll try to rebuild from scratch and share a working model.

Yeah, I’d recommend starting from scratch :+1:

While I’m still working on fixing the TKinter threading issue, more general question:

Wouldn’t it be a neat feature to make plotly figure passable to Graph objects? Or is it already? What would the limitations for that be? Why is not the recommended appraoch? Or is it just not recommended to do this with matplotlib figures which have been converted to plotly objects?

Yeah, it is already. They are comptaible. You can either use go.Figure or just {}. They’ll compile down to the same thing in the end.

The only difference between using the go.* classes and regular lists and dictionaries is that the go classes give you validation (although we’re adding validation in and typeahead. I know the syntax well enough by now that I just use regular dictionaries and lists, but I don’t expect that to be the case for everyone.

So, you could pass in the mpl_to_plotly figure directly into the figure property of the dcc.Graph. That being said, mpl_to_plotly isn’t necessarily complete and we’re not investing any more resources in improving it. That being said, we’re also not planning on removing it either.