✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Animating a variable number of traces in each frame

Hello, I am new to Plotly. I am trying to animate a set of frames where each frame may have different number of traces using Plotly.py. For example:

  • Frame 1 has 2 Scatter traces, coloured (fillcolor) red and blue.
  • Frame 2 has 4 Scatter traces, coloured red, red, blue, blue.
  • Frame 3 has 4 Scatter traces, coloured red, red, red, blue.
  • Frame 4 has 2 Scatter traces, coloured red and blue.

Is it possible to do this with Plotly? My progress so far:

  • I pass an array of 4 traces to the data argument of go.Figure(), but the third and fourth Scatters are generated as go.Scatter(x=[None], y=[None])
  • Similar mechanism is adopted for the frames argument.
  • When the frame has third and fourth traces, these traces are constructed with the corresponding fillcolor.

The problem is, this results in the following behaviours.

  • When there are supposed to be 4 traces, only two traces are filled with colour. The rest are shown as their outlines.
  • The trace legend shows incorrect colours. In the first frame, the colours for the third and fourth traces seem to be random (I am fine with this). However, in the second frame, the same colours persist, while they should have been updated. This will only be fixed after you click on the legend. The same with the traces’ names.

Here are two images showing the above behaviour.

Frame i

Frame i+1 (after shape transformation)

Does anyone know how I can improve my code?

Many thanks,
Nicholas