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

# Animations in JavaScript

How to animate charts in JavaScript with the animate API.

New to Plotly?

Plotly is a free and open-source graphing library for JavaScript. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

### Animating the Data

The animate command lets you add dynamic behavior to Plotly graphs in a number of different ways. At its core, Plotly.animate transitions traces to a new state or sequence of states. When you tell Plotly to animate, it merges the properties you've supplied into the current state of the plot. Therefore to animate a trace, you must first plot the trace you wish to animate.

The example below transitions to new y-values each time the button is pressed. Since the transition animation occurs within a frame, frame.duration must be set at least as long as transition.duration. Note that to prevent artifacts while animating, the default line simplification algorithm is explicitly disabled. Currently, only scatter traces may be smoothly transitioned from one state to the next. Other traces are compatible with frames and animations but will be updated instantaneously.

Plotly.newPlot('myDiv', [{
x: [1, 2, 3],
y: [0, 0.5, 1],
line: {simplify: false},
}]);

function randomize() {
Plotly.animate('myDiv', {
data: [{y: [Math.random(), Math.random(), Math.random()]}],
traces: [0],
layout: {}
}, {
transition: {
duration: 500,
easing: 'cubic-in-out'
},
frame: {
duration: 500
}
})
}


### Animating the Layout

The example below transitions to a new axis range each time the button is pressed. A present limitation of the animate API is that only one of either data or layout may be smoothly transitioned at a time. If both are provided, the data will be updated instantaneously after the layout is transitioned.

var n = 500;
var x = [], y = [];
for (var i = 0; i < n; i++) {
x[i] = i / (n - 1);
y[i] = x[i] + 0.2 * (Math.random() - 0.5);
}

Plotly.newPlot('myDiv', [{
x: x,
y: y,
mode: 'markers'
}], {
xaxis: {range: [0, 1]},
yaxis: {range: [0, 1]}
});

function zoom() {
var min = 0.45 * Math.random();
var max = 0.55 + 0.45 * Math.random();
Plotly.animate('myDiv', {
layout: {
xaxis: {range: [min, max]},
yaxis: {range: [min, max]}
}
}, {
transition: {
duration: 500,
easing: 'cubic-in-out'
}
})
}


### Defining Named Frames with Plotly.addFrames

The above examples pass the data itself through the Plotly.animate command. You may instead predefine named frames through the Plotly.addFrames command. Then, instead of passing frames through Plotly.animate, you may simply refer to a frame by name.

Similar to traces, frames are assigned a serial index as they are added. Frames may be updated by passing an array of frame indices. For example, the command to update the frame with index 2 would be Plotly.addFrames('myDiv', [{...}], [2]). Frames can be similarly deleted with, for example, Plotly.deleteFrames('myDiv', [2]).

The following example uses frames together with an updatemenu for interactive transitions.

var frames = [
{name: 'sine', data: [{x: [], y: []}]},
{name: 'cosine', data: [{x: [], y: []}]},
{name: 'circle', data: [{x: [], y: []}]},
];

var n = 100;
for (var i = 0; i < n; i++) {
var t = i / (n - 1) * 2 - 1;

// A sine wave:
frames[0].data[0].x[i] = t * Math.PI;
frames[0].data[0].y[i] = Math.sin(t * Math.PI);

// A cosine wave:
frames[1].data[0].x[i] = t * Math.PI;
frames[1].data[0].y[i] = Math.cos(t * Math.PI);

// A circle:
frames[2].data[0].x[i] = Math.sin(t * Math.PI);
frames[2].data[0].y[i] = Math.cos(t * Math.PI);
}

Plotly.newPlot('myDiv', [{
x: frames[0].data[0].x,
y: frames[0].data[0].y,
line: {simplify: false},
}], {
xaxis: {range: [-Math.PI, Math.PI]},
yaxis: {range: [-1.2, 1.2]},
buttons: [
{method: 'animate', args: [['sine']], label: 'sine'},
{method: 'animate', args: [['cosine']], label: 'cosine'},
{method: 'animate', args: [['circle']], label: 'circle'}
]
}]
}).then(function() {
});


### Animating Sequences of Frames

The above examples have used one frame at a time. Whether passing objects as frames or referring to frames by name, you may pass multiple frames together in an array. If null or undefined is passed as the second argument (i.e. Plotly.animate('myDiv')), then all defined frames will be animated in sequence.

The third argument of Plotly.animate contains animation options. The transition duration defines the amount of time spent interpolating a trace from one state to another (currently limited to scatter traces), while the frame duration defines the total time spent in that state, including time spent transitioning. The example below has two frames, each with their own transition and frame timing.

Plotly.newPlot('myDiv', [{
x: [0, 0],
y: [-1, 1],
}], {
xaxis: {range: [-Math.PI, Math.PI]},
yaxis: {range: [-1.3, 1.3]}
}).then(function () {
{
data: [{x: [1, -1], y: [0, 0]}],
name: 'frame1'
}, {
data: [{x: [0, 0], y: [-1, 1]}],
name: 'frame2'
}
]);
})

function startAnimation() {
Plotly.animate('myDiv', ['frame1', 'frame2'], {
frame: [
{duration: 1500},
{duration: 500},
],
transition: [
{duration: 800, easing: 'elastic-in'},
{duration: 100, easing: 'cubic-in'},
],
mode: 'afterall'
})
}


### Animating Many Frames Quickly

By default and to ensure any properties that cannot be animated are applied to the plot, a full redraw occurs after each transition. This is generally desirable, but hurts performance when you wish to animate frames as quickly as possible. The example below performs a live simulation of the Lorenz attractor and greatly improves the performance by eliminating the redraw with redraw: false.

var n = 100;
var x = [], y = [], z = [];
var dt = 0.015;

for (i = 0; i < n; i++) {
x[i] = Math.random() * 2 - 1;
y[i] = Math.random() * 2 - 1;
z[i] = 30 + Math.random() * 10;
}

Plotly.newPlot('myDiv', [{
x: x,
y: z,
mode: 'markers'
}], {
xaxis: {range: [-40, 40]},
yaxis: {range: [0, 60]}
})

function compute () {
var s = 10, b = 8/3, r = 28;
var dx, dy, dz;
var xh, yh, zh;
for (var i = 0; i < n; i++) {
dx = s * (y[i] - x[i]);
dy = x[i] * (r - z[i]) - y[i];
dz = x[i] * y[i] - b * z[i];

xh = x[i] + dx * dt * 0.5;
yh = y[i] + dy * dt * 0.5;
zh = z[i] + dz * dt * 0.5;

dx = s * (yh - xh);
dy = xh * (r - zh) - yh;
dz = xh * yh - b * zh;

x[i] += dx * dt;
y[i] += dy * dt;
z[i] += dz * dt;
}
}

function update () {
compute();

Plotly.animate('myDiv', {
data: [{x: x, y: z}]
}, {
transition: {
duration: 0
},
frame: {
duration: 0,
redraw: false
}
});

requestAnimationFrame(update);
}

requestAnimationFrame(update);


### Object Constancy

For scatter traces, you may wish to retain a marker's identity as it is updated. If you include an array of string ids with the trace, the marker identity will be retained. By shuffling the ids, the example below shuffles the markers each time the button is pressed.

function shuffleInPlace(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}

var ids = ['1', '2', '3', '4', '5', '6'];

Plotly.newPlot('myDiv', [{
x: [1, 0.5, -0.5, -1, -0.5, 0.5],
y: [0, 0.866, 0.866, 0, -0.866, -0.866],
marker:{size:14,
'#F06292', '#F48FB1']},
ids: ids,
mode: 'markers'
}], {
xaxis: {range: [-3, 3]},
yaxis: {range: [-2, 2]}
});

function animateShuffle() {
shuffleInPlace(ids);
Plotly.animate('myDiv', [{
data: [{ids: ids}]
}]);
}


### Frame Groups and Animation Modes

The following example combines many of these concepts to draw a glass filling with water.

The first row of buttons animates a different set of predefined frames by changing the second argument of Plotly.animate. Passing null or undefined animates all defined frames in sequence, while passing an array of strings (here, the frames in reverse) animates a specific sequence of frames. By passing a plain string (here, lower or upper), it filters the animated frames to those with a group property equal to that name. The stop button is accomplished by interrupting the current animation with an empty list of frames, therefore simply stopping the animation at the end of the current frame.

The second row of buttons animates all frames with different animation modes. The mode option defines whether an animation either interrupts or follows the current animation. immediate mode discards all queued frames and begins a new sequence immediately. The next mode is very similar but doesn't begin the new animation until the end of the current frame. Finally, afterall queues the new frames so that the new animation begins only after all previous animations have completed.

var i, j, t, x, y, name;
var frames = [];
var nFrames = 10;
var n = 80;
var reverseFrames = [];

for (i = 0; i < nFrames; i++) {
var fill = 0.1 + 0.9 * i / (nFrames - 1);
x = [-1];
y = [0];

// A wave across the top:
for (j = 0; j < n; j++) {
t = j / (n - 1);
x.push(-1 - fill + (2 + 2 * fill) * t);
y.push(fill + 0.05 * Math.sin(t * Math.PI * 2 * i));
}

// Close the loop to draw the water:
x.push(1, -1);
y.push(0, 0);

// Choose a name:
name = 'frame' + i;

// Store it in an array so we can animate in reverse order:
reverseFrames.unshift(name);

// Create the frame:
frames.push({
name: name,
data: [{x: x, y: y}],
group: i < nFrames / 2 ? 'lower' : 'upper'
})
}

Plotly.newPlot('myDiv', [{
// Set up the initial water:
x: frames[0].data[0].x,
y: frames[0].data[0].y,
mode: 'lines',
fill: 'toself',
showlegend: false,
line: {simplify: false}
}, {
// Draw a glass:
x: [-1, 1, 2.1, -2.1, -1],
y: [0, 0, 1.1, 1.1, 0],
mode: 'lines',
fill: 'toself',
showlegend: false,
fillcolor: 'rgba(0, 0, 0, 0.1)',
line: {color: 'rgba(100,100,100,0.2)'}
}], {
xaxis: {range: [-3, 3]},
yaxis: {range: [-0.1, 1.5]}
}).then(function() {
// Add the frames so we can animate them:
});

// Stop the animation by animating to an empty set of frames:
function stopAnimation () {
Plotly.animate('myDiv', [], {mode: 'next'});
}

function startAnimation (groupOrFrames, mode) {
Plotly.animate('myDiv', groupOrFrames, {
transition: {
duration: 500,
easing: 'linear'
},
frame: {
duration: 500,
redraw: false,
},
mode: mode
});
}