Chuyển đến nội dung

Bài 34 · Interactivity and Animation

Animations and Frames

Animate Plotly charts with Plotly Express animation_frame and with go.Frame: play and pause buttons, a frame slider, transitions, fixed axes and bar chart races.

An animation is the easiest way to show change over time: countries moving across a scatter plot as the years pass, a distribution that updates every week, a ball following an orbit. Plotly animations are not video files. They are a list of frames, each frame holding the data (and optionally layout) for one moment, plus a play button and a slider that step through the list. Because it is all in the figure, an animation works in a notebook, a Dash app or an exported HTML page.

Animation with Plotly Express

The shortcut is animation_frame="column". One frame is created for each distinct value of that column, in sorted order. animation_group tells Plotly which rows are "the same object" from frame to frame, so a bubble glides smoothly instead of popping in and out.

Python Gapminder bubbles over time

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at what Plotly Express generated: a list of 12 frames (one every five years), a play/pause menu and a slider with 12 steps. These are exactly the updatemenus and sliders you already know, wired to the "animate" method.

Always fix the axis ranges (range_x, range_y), as shown above. Without them, Plotly recomputes the axes in every frame, and the whole picture jumps around, which makes the motion unreadable.

Useful settings:

  • fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 500 changes the time per frame in milliseconds.
  • fig.layout.updatemenus[0].buttons[0].args[1]["transition"]["duration"] = 300 changes the tween time between frames.
  • px.bar(..., animation_frame=..., range_y=[0, max]) animates bars; px.choropleth(..., animation_frame=...) animates a map.

Frames by hand: go.Frame

Behind the scenes a go.Figure has frames, a list of go.Frame objects. Each frame has a name (what the slider points to) and a data list. The data overrides the base figure's traces at the same index. A figure whose base data is the first frame and whose frames list holds the rest is a complete animation once you add the controls.

Python A hand-built animation: a point on a circle

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details matter here. traces=[1] in the frame says "this frame only changes trace number 1", so the gray circle is not redrawn. And redraw: False tells Plotly it only needs to update the markers, not rebuild the whole plot, which is much faster. For plots with a heavy layout (maps, 3D) keep redraw on.

The same idea in Plotly.js

In Plotly.js you call Plotly.addFrames (or pass frames to newPlot) and Plotly.animate to play. Here a bar chart "race" reorders bars as the values change.

Bars that grow, frame by frame (Plotly.js)

Press Play, or drag the slider to scrub through time. mode: "immediate" on the slider steps makes the chart jump to that frame without waiting for the previous one to end.

Frames, size and design

flowchart LR
    A["Base figure: data + layout"] --> B["frames: go.Frame list"]
    B --> C["updatemenus: Play / Pause (method animate)"]
    B --> D["sliders: one step per frame (method animate)"]
    C --> E["Browser steps through frames"]
    D --> E

The figure stores every frame; the controls only tell the browser which frame to show next.

  • Size. Each frame stores its data, so a 100-frame animation of 10,000 points is a large page. Animate summaries, not raw data.
  • Meaning. Animation is good for change and engaging stories, but poor for precise comparison across time, because viewers cannot hold earlier frames in memory. Pair it with a static small-multiples view, or a line chart of the key series.
  • Accessibility. Provide the slider so people can pause and step, and avoid fast flashing.
  • Not for real-time. Frames are precomputed. For a stream of new values use a Dash dcc.Interval (see Dash callbacks and live graphs).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does animation_group do in px.scatter?

    Without animation_group, Plotly cannot match points between frames and they appear and disappear instead of gliding.
  2. 2. Why should you set range_x and range_y in an animated chart?

    Autoscaling per frame makes the whole plot shift, which hides the real movement.
  3. 3. What does traces=[1] on a go.Frame mean?

    The frame's data list is applied to the listed trace indexes, leaving other traces untouched.
  4. 4. Which tool is right for a chart that must update with brand-new values every second?

    Frames hold precomputed data. Live data needs a periodic callback that returns a new figure.

Summary

  • Frames are a list of data snapshots; the play button and slider use the animate method.
  • px functions create everything from animation_frame and animation_group.
  • Fix axis ranges, and use traces and redraw=False in hand-built frames for speed.
  • Control timing with frame.duration and transition.duration.
  • Animations show change nicely but are precomputed: use callbacks for live data.

Next: Your First Dash App

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.