Black Lives Matter. Please consider donating to Black Girls Code today.

Dynamic animation title/annotation

Hi all,

How do you propose to add dynamic title/annotation to animations that changes per frame?

I am currently using plotly express and updating the fig.layouts but it’s still static per frame…

Best,

Hi @vitaminc,

To update each frame layout add the following lines of code

for k in range(len(fig.frames)):
    fig.frames[k]['layout'].update(title_text=f'My title {k}')

and if in your updatemenus or sliders definition, redraw=False, change it to redraw=True.

3 Likes

Hi @empet I tried to use your suggestion for the following example but it doesn’t seem to work.

import plotly.express as px

df = px.data.gapminder()
text = df.groupby("year").pop.mean().astype(int).values

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])\
        .update_layout(
#                        title="Avg Population: {}".format(text[0]), 
                       title_x=0.5)


for i, frame in enumerate(fig.frames):
    frame.layout.title = "Avg Population: {}".format(text[i])
    
for step in fig.layout.sliders[0].steps:
    step["args"][1]["frame"]["redraw"] = True

I tried @baobab 's code and it kinda works but then stops working when you pause the animation and play it again. Bug?

gapminder

1 Like

@RenaudLN this is weird. Apparently I’m the only one who didn’t get this code working. I tried on Jupyter lab and notebook and there are not titles.

+1 to this question. I’ve tried @empet and @baobob 's solutions (running plotly.express v4.12.0 in Jupyter Notebook v6.1.4) but neither results in a title rendering for me, let alone updating dynamically.

Update: I was able to get this to work, but for me rather than iterating thru sliders[0].steps to set 'redraw': True I iterated thru updatemenus[0].buttons:

for button in fig.layout.updatemenus[0].buttons:
    button['args'][1]['frame']['redraw'] = True

for k in range(len(fig.frames)):
    fig.frames[k]['layout'].update(title_text=f'My title {k}')