How to animate line in scatter plot using plotly express?

Viewed 668

Consider official example for scatter plot animation

import plotly.express as px
df = px.data.gapminder()
px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])

this results in a plot in which markers are getting animated. However, I want to animate the connecting lines too which is not directly possible. I tried to update mode and marker properties for the frames like fig.frames.data[n].mode=markers+lines but still no luck. Could someone let me know where I am going wrong.

Cheers, DD

1 Answers

If you by animate the connecting lines means connecting, for example, all markers illustrating Asia etc in the example above, then adding the following to your code will produce the plot below.

fig.for_each_trace(lambda t: t.update(mode = 'lines+markers'))
for fr in fig.frames:
    for d in fr.data:
        d.update(mode='markers+lines')

Plot:

enter image description here

Complete code:

import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90],
           # mode = 'markers+lines'
           height = 600, width = 1000
          )

# lineas and markers on first display
fig.for_each_trace(lambda t: t.update(mode = 'lines+markers'))

# lineas and markers on animation frames
for fr in fig.frames:
    for d in fr.data:
        d.update(mode='markers+lines')
        
fig.show()
Related