How to make an animated bubble chart in JavaScript
An animated bubble chart plays a scatter plot one year at a time. This post builds the Gapminder chart from World Bank data, with trails, labels and controls.
Made with OpenChart. How to build this scatter plot
China’s life expectancy rose from 33.4 years in 1960 to 64.8 in 1981, and through all of those years its GDP per person stayed under $200, according to the World Bank. An animated bubble chart shows that climb as movement: each country is a bubble placed by income and life expectancy, sized by population, and the bubbles move one year at a time from 1960 to 2023.
Hans Rosling made this chart famous in his Gapminder talks. In OpenChart it is a scatter plot spec with two extra encoding fields, time and key, and one row per country per year.
Made with OpenChart. How to build this scatter plot
The chart runs for 25 seconds, about 400 milliseconds for each of the 64 years, and holds on 2023 for a second and a half. The strip under it plays, pauses and scrubs to any year. With focus on the strip, the arrow keys step one year at a time.
China’s 1960 figure falls in the famine that followed the Great Leap Forward, so part of the early climb is recovery: life expectancy was back to 51 by 1962.
The data: one row per country per year
A playback chart reads long data, one row for each country in each year:
const rows = [
{ country: "China", region: "Asia & Pacific", year: 1960, gdp: 90, life: 33.4, pop: 667070000 },
{ country: "China", region: "Asia & Pacific", year: 1961, gdp: 76, life: 40.2, pop: 660330000 },
{ country: "India", region: "Asia & Pacific", year: 1960, gdp: 85, life: 45.6, pop: 435990338 },
// ...one row per country and year
];The three World Bank indicators (GDP per capita, life expectancy at birth and total population) come as separate tables keyed by country code and year. Join them on those two columns before building the rows. This post uses 62 large countries from OpenData’s mirrors of the three indicators, with a region assigned to each.
Leave a missing value as null rather than 0. A country with no value in a year has no bubble that year, so it enters the chart when its data starts and fades out when it stops. Only 51 of the 62 countries have all three values in 1960. Russia’s series starts in 1988, so its bubble appears that year, and Cuba’s GDP figures stop after 2020, so its bubble fades out.
A gap between two observed years is filled by interpolating between them; playback.gaps: "hold" carries the last value forward instead, and "drop" hides the bubble until its next value.
Each country gets one row per year. Two rows with the same country and year stop the chart with an error that names them and asks you to aggregate first.
A complete spec
The spec is an ordinary bubble chart, mark: "point" with x, y, size and color, plus two fields. encoding.time names the field that splits the rows into periods, and encoding.key names the field that identifies a bubble from one year to the next. This one keeps the 10 most populous countries and every fifth year, 130 rows, so the whole spec fits on the page.
Made with OpenChart. How to build this scatter plot
The chart at the top of this post is the same encoding over all 3,968 rows, with playback.duration set to 25 seconds.
The key is required. Without it the chart can’t tell which 1961 bubble is the same country as which 1960 bubble, and validation stops with “point charts with encoding.time need encoding.key”. The time field can be temporal, quantitative or ordinal. Years and dates sort by value, and four-digit years print as plain years in the period label and the readout.
Pass a container and the spec to createChart:
import { createChart } from "@opendata-ai/openchart-vanilla";
const chart = createChart(document.getElementById("chart"), spec);The control strip takes 44 pixels under the chart, so give the container room for both.
Log scale and fixed axes
GDP per capita runs from $12 (Myanmar in 1966) to $81,032 (the United States in 2023), and on a linear axis every country below $5,000 would sit in a pile at the left edge. On the log axis each step of ten times the income gets the same width. Bubbles also move in log space between years, so a country that goes from $100 to $10,000 passes $1,000 halfway through the step, which is where the eye expects it.
The axes are computed once from all 64 years and never move while the chart plays. A reader can compare a bubble’s 1975 position with its 2023 position against the same gridlines, and a bubble never jumps because the axis under it rescaled.
The World Bank figures are in current US dollars, not adjusted for inflation or for prices in each country. Part of the drift to the right is inflation, and exchange rates move the bubbles too. Iraq’s figure falls from $10,261 in 1990 to $23 in 1991, which sends its bubble to the far left of the chart. Say which measure you plotted in the subtitle, as this one does.
A value of zero or less can’t sit on a log scale, so playback treats it as missing and warns with the count of values it dropped.
Speed, labels and the year
Everything about playback lives in the top-level playback block, which the playback docs cover option by option. By default a chart takes 700 milliseconds per period, with the total kept between 8 and 90 seconds; 64 years would run 44.8 seconds. playback.duration sets the total in milliseconds, 25000 here, and playback.step sets the time per period instead. Set one or the other, not both. The last frame holds for 1.5 seconds (holdEnd), and loop: true starts over after it.
playback.labels names the countries whose name is drawn beside the bubble for the whole run. Labels are never hidden to avoid a collision, so none of them blinks on and off mid-run, but two labelled countries that end up close together will overlap. Label a few that stay apart. This chart labels China, India and Nigeria, whose life expectancy in 2023, 54.5 years, was the lowest of the 62 countries.
The large faint year behind the bubbles is the period label. It sits in the middle of the plot by default and uses the time field’s format. playback.period: { format, position } changes the format or moves it to "top-right" or "bottom-left", and period: false hides it.
Trails
playback.trails draws each named country’s path as a thin line with a dot for every year it has passed. true traces every country, which with 62 countries covers the chart in lines, and a list of names traces only those.
Made with OpenChart. How to build this scatter plot
South Korea and China both reached a life expectancy of 60 on about $160 a person, in 1967 and 1974, and India got there in 1994 at $348. South Korea’s path then runs right, to $35,674 by 2023, while India’s is still under $3,000.
Controls and the playback API
playback.autoplay defaults to "visible", which starts the chart once a quarter of it is in view. true starts it at mount and false waits for the play button. playback.controls: false removes the strip; if autoplay is also on, the engine warns, because a reader then has no way to pause moving content, which WCAG 2.2.2 requires.
Readers who have asked their system for reduced motion get no autoplay, and the chart opens on the last year. The scrubber and arrow keys still work, and they step from year to year without sliding the bubbles between them. animation: false in the spec does the same for every reader.
The chart that createChart returns has a playback property, null for charts without encoding.time:
const playback = chart.playback;
playback?.pause();
playback?.seek(1980 - 1960); // a zero-based period index; fractions land between years
playback?.setSpeed(2); // twice as fast as the authored duration
playback?.play();
const unsubscribe = playback?.on("period", (period) => {
caption.textContent = period.label;
});getState() returns the playhead as a continuous period index, whether the chart is playing, the speed, whether it has ended and the current period. The period event fires as the playhead crosses each year and when a seek lands, which is enough to keep a caption or a step in a scrolling story in sync.
The rest of the chart keeps working while it plays: tooltips follow the bubbles, and clicking a region in the legend hides its countries without resetting the axes. After pausing, stepping or scrubbing, a screen reader hears the year and how many countries are on the chart.
React, Vue and Svelte
The framework packages render the same spec with their Chart component, and the chart’s ref reaches the same instance:
import type { ChartSpec } from "@opendata-ai/openchart-core";
import { Chart, type ChartHandle } from "@opendata-ai/openchart-react";
import { useRef } from "react";
export function WealthAndHealth({ spec }: { spec: ChartSpec }) {
const chart = useRef<ChartHandle>(null);
return (
<>
<Chart ref={chart} spec={spec} style={{ height: 600 }} />
<button type="button" onClick={() => chart.current?.instance?.playback?.seek(1980 - 1960)}>
Show 1980
</button>
</>
);
}Vue and Svelte import Chart from @opendata-ai/openchart-vue and @opendata-ai/openchart-svelte.
Static frames and exports
Server renders and static exports show one frame, the last year by default. renderStaticSVG(spec, { t }) from @opendata-ai/openchart-vanilla/static takes the period index to draw, so t: 20 draws 1980, and compileChart takes the same index as playbackT. Use a static frame for a social preview image or a no-JavaScript fallback, and remove it before mounting the live chart. Trails are drawn up to the year you pick.
On a mounted chart, chart.export("svg") and chart.export("png") save the frame on screen with its trails, so seek to the year you want first. The export docs cover the options both formats take.
chart.export("gif") on a playback chart records the whole run, 1960 through 2023 and the hold on the last year, for newsletters and other pages that can’t embed a live chart. It needs the optional gifenc package. A race exports the same way with player.export("gif"), as How to make a bar chart race in JavaScript shows.
The bubble playback docs page covers keys, trails, labels and the fixed axes in more detail.