2

I'm working on my animation chart with plotly express and it works well. But I want the animation_frame (which is the date on my plot) shown on the plot (shown on the red square on the plot). How to do this?

I didn't find the setting about animation_frame on the Internet.

I'm following the example of this blog

Here's the plot and the red square is the position where I want to add the animation_frame. enter image description here

Derek O
  • 16,770
  • 4
  • 24
  • 43
  • Welcome to stackoverflow. Please checkout the [tour](https://stackoverflow.com/tour), [editing help](https://stackoverflow.com/editing-help) and [How to Ask](https://stackoverflow.com/questions/how-to-ask) – Jubin Justifies Apr 13 '23 at 06:20
  • @CarterZhang it would be much easier for us to help you if we can reproduce your figure. are you following [the example](https://plotly.com/python/animations/#animated-figures-with-plotly-express) from the documentation, or is the image you included just meant to illustrate what you want to see in your figure? – Derek O Apr 13 '23 at 21:48

1 Answers1

0

When you create a figure using animations in plotly, each trace is stored in a frame, and a tuple of all of the frames are stored in fig.frames. What we can do is add a go.Scatter trace to each frame with text in the upper right corner of your figure that corresponds to the year – and since we supplied the argument animation_frame="year", each frame in fig.frames has the property "name" equal to the year.

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

## add the text as a trace to it shows up initially
fig.add_trace(go.Scatter(
    x=[45000],
    y=[85],
    text=fig.frames[0]['name'],
    mode='text',
    textfont=dict(size=20),
    showlegend=False,
))

## add the text to each individual frame
for frame in fig.frames:
    frame.data = frame.data + (
        go.Scatter(
            x=[45000],
            y=[85],
            text=frame.name,
            mode='text',
            textfont=dict(size=20),
            showlegend=False,
        ),
    )

fig.show()

enter image description here

Derek O
  • 16,770
  • 4
  • 24
  • 43