Black Lives Matter. Please consider donating to Black Girls Code today.
Dash Enterprise delivers an incredible 21x cost savings 💸Download the e-book!

Speeding up `fig.add_shape()` calls in Python

Hello everyone,

I am working on a visualization application in python right now to visualize data in multiple subplots. One of the things I am doing is in each subplot, plotting vertical lines to indicate when some certain things have happened (it is time variant data).

Using cProfile, I was able to identify a fairly large portion of my time in each method goes to the add_shape() method call.

In each of those subplots, I am basically calling the following line:

            fig.add_shape(
                plotly.graph_objects.layout.Shape(
                    type="line",
                    xref="x",
                    yref="y",
                    x0=x0
                    y0=y0,
                    x1=x1,
                    y1=y1,
                    name=name,
                    line=dict(color=line_color, width=3, dash='dot'),
                ),
                row=row,
                col=col,
            )

Is anyone aware of a way to speed this up? Thank you in advance!

Hi @agd, welcome to the forum! It turns out we have an open issue for this https://github.com/plotly/plotly.py/issues/2141 :-), and it’s tagged for the next release 4.6! Feel free to comment in this issue.

Thank you for the warm welcome, @Emmanuelle! That’s great news. I had no idea, so thank you for the heads up!

Hi again @agd, I must have read your question too fast because my answer was actually about speeding up the code-writing time by having a one-liner convenience function, not about the execution time. In your code, how many shapes do you typically add and how much time does it roughly take?

@Emmanuelle I saw some of the issues myself, and I definitely would love some of the features proposed, such as infinite vertical and horizontal lines similar to MatPlotLib

For reference, we are currently creating x3 individual figures, each of them with their own sub plots. 2 of these figures/html pages have 12 subplots, and the last pages has 5 subplots. In each of those subplots, we need to plot 8 vertical lines across.

I did a quick test, and to plot those 232 lines as well as the other data, it took a sum total of 23.1s to prepare and plot all the data, 11.5 seconds were caused by plot_shape() calls.

I will say, I have overcome this issue by plotting these vertical lines as simple scatter traces now, which helps quite a bit.

1 Like

i signed up for this forum just to thank you from the bottom of my heart. i am new to dash, so i was really panicking. that solution worked wonders for me. again thank you for sharing it :slight_smile:

1 Like