Calling Figure() is very slow

Hello,

i am running some queries on a normal sized dataframe of 1m rows. All my calculations take 0.04 seconds but just calling Figure() consumes 0.25s. Is there any way to speed it up? Why does it take so long?

I also noticed that if i repeat Figure() calls under the first one they get executed in lighting speed instead of needing 0.25s

I am using also Dash. The crazy thing is that if i use a variable outside of the callback function like this:

fig = Figure()

@callback(...)
def my_callback(...)
     global fig
     .... add traces to fig
     return fig

It’s fast again. The strange thing is that the fig is always displaying the correct data. Why is this possible? Shouldn’t the global fig include the traces from the previous call?

I have

app.run_server(debug=True, host="0.0.0.0", threaded=False, processes=4)

and the expected behavior is only happening when processes=1

If i do

fig = Figure()

@callback(...)
def my_callback(...)
     fig = Figure()
     .... add traces to fig
     return fig

without the def global it works and is faster as well.

Hi,

I believe the 0.25s comes from some imports that are made the first time you call go.Figure in your application. You can try to profile the code to see if my assumption is correct. Figure can also be slow if you are constructing it with traces (it is not your case), since there are some data validations being made.

I wouldn’t rely on global variables, as it is well documented a bad idea… Instead, you can skip the Figure construction in Dash by using/updating the “figure” dictionary.

Dash serializes all the inputs and outputs in callbacks to JSON, including go.Figure objects. For instance, if you have a callback using the “figure” prop from a dcc.Graph component as Input or State, you can see that the fig is passed to the callback as a dictionary and not a go.Figure… You can make all sorts of updates and modifications by manipulating the dictionary, it just requires some familiarity with its structure (you can see an example here).

Hope this helps!

1 Like