How to set scatter plot marker color in plotly express animations

Iโ€™m using px.scatter to create an animated dot plot that goes through the years with the play button.

fig = px.scatter(df, x="Rate", y="Country Name", color="Gender", animation_frame="Year",
                 range_x=[4,19], range_y=[-0.5,4.5]
      )

That works beautifully; however, Iโ€™m trying to change the default color of the markers for both genders (male,female).

If I run the script below:

fig.data[0]['marker'].update(color='#bff68e') #green
fig.data[1]['marker'].update(color='#fda026') #orange

the color changes correctly for both gender markers, but only for the FIRST frame. The subsequent frames go back to their default color. So I created a FOR loop to go over all the frames:

for x in fig.frames:
    x.data[0]['marker']['color'] = '#bff68e'
    x.data[1]['marker']['color'] = '#fda026'

This works fine. But I was wondering, Is there a faster and simpler way to update the marker color for all frames without creating a for loop?

@adamschroeder

If you are displaying fig.frames and see that each Frame.data has set the color['marker'], then you donโ€™t have another faster solution than creating a loop. This means that the frame definition doesnโ€™t update only the attributes of fig.data that change from frame to frame, but also the constant value attributes.

Usually if the fig data is defined like in this example:

fig = go.Figure()

fig.add_scatter(x=np.arange(10),
                         y=1+3*np.random.rand(10),
                         marker_size=6, marker_color='red', line_color='blue') #trace of index 2

and we want in each frame to change only point positions, not other properties, then the frames are defined as follows

fig.frames =  [go.Frame(data=[go.Scatter(y=2+3*np.random.rand(10))],
                                    traces=[0]) for k in range(20)]

Adding in Frame defintion the same color like in the corresponding fig.data is a superfluous setting.
I think that in the plotly express all fig.data settings are repeated in Frame definition, for generality, to let users customize the fig appearance after its definition

1 Like