简体   繁体   中英

How can I force Plotly animation to start by the last frame?

I would like to change the 'default' frame of my animated chart and force it to use the last date as default when the Dash application is rendered. How can I do this?

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

I'm trying some different approaches, like something like it:

fig.layout['sliders'][0]['active'] = 11

and

frame = -1
fig = go.Figure(fig.frames[frame].data, fig.frames[frame].layout)
fig

but it's not being reflected correctly on the chart.

Could someone give me a direction on how I can I found references about it?

I want to force the graph to start on the last year.

The problem is that in fig.data you have the first frame. I found a workaround generating a new figure.

import plotly.express as px
import plotly.graph_objects as go

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

# New figure
fig2 = go.Figure()

# add last frame traces to fig2
for tr in fig.frames[-1].data:
    fig2.add_trace(tr)

# copy the layout
fig2.layout = fig.layout

#  copy the frames
fig2.frames = fig.frames

# set last frame as the active one
fig2.layout['sliders'][0]['active'] = len(fig.frames) - 1

fig2

Thank you very much for your answer bro; It works.

I had built a solution that is similar to yours but with some differences:

import plotly.express as px
import plotly.graph_objects as go

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

last_frame_num = len(fig.frames) -1

fig.layout['sliders'][0]['active'] = last_frame_num

fig = go.Figure(data=fig['frames'][-1]['data'], frames=fig['frames'], layout=fig.layout)

fig

Anyway, I appreciate a lot your attention/support, it's ever great to have more options when implementing something!

Thank you very much; Best Regards, Leonardo

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