简体   繁体   中英

How to animate line in scatter plot using plotly express?

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

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:

在此处输入图像描述

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM