I often find myself in a situation where I want to see something animated 'live'. With this I mean I have some data, a function to update that data let's call it step[]
and then want to display the data as it updates. I never found a good way to do this.
To make it more clear let's look at an example.
Initialise data:
n = 100;
x = RandomReal[1, n]*.01;
f[x_] := Mod[x 1.01, 1]
Step function:
step[] := Module[{}, x = f[x]]
Display code:
ListPlot[{Cos[2 \[Pi] x], Sin[2 \[Pi] x]}\[Transpose],
AspectRatio -> 1, PlotRange -> {{-1, 1}, {-1, 1}}]
After looking at the documentation I could come up with two ways to animate this. In one cell run:
animationRunning = True;
While[animationRunning, step[]; Pause[.1]]
In another run:
Dynamic[ (* display code *) ]
This does what I want but it locks up the interpreter (I can't run another cell) and it feels like it's not the intended way to animate because it doesn't make use of the functions intended for animation.
Another way I found is to run this in one cell:
Dynamic[Refresh[step[], UpdateInterval -> 2]]
and run Dynamic[ (* display code *) ]
in another cell again.
This behaves better than the while loop but it completely ignores the UpdateInterval: it just runs as fast as it can. I want some control over the speed.
So is there any proper way to do these kinds of animations?
Based on MassDefect's answer I was finally to make what I wanted
Here's the code
Animate[step[]; a;, {a, Infinity}, RefreshRate -> 3]
Dynamic[ListPlot[{Cos[2 \[Pi] #], Sin[2 \[Pi] #]}\[Transpose] &@x,
AspectRatio -> 1, PlotRange -> {{-1, 1}, {-1, 1}}]]
Benefits of this code
- Easy to pause/unpause
- Controllable speed
- Arbitrarily complex code in the
step[]
function - Runs in real time (not predefined like ListAnimate)
Animate[]
orAnimator[]
almost do what I want but those functions only work for animations that are parametrised by some variable and don't run continuously. I'm used to there being some kind of animation-loop likeFuncAnimation
in Python (Matplotlib) orRequestAnimationFrame
in Javascript and I can't find such a function in Mathematica. $\endgroup$ListPlot[{Cos[2 \[Pi] x], Sin[2 \[Pi] x]}\[Transpose]...
ListPlot
takes a list, not a function. The Transpose does nothing. $\endgroup$