Animated phase portraits
During a recent residency at the Hambidge Center, I began working on a series of animated representations of dynamical systems. In June 2025, I was a multidisciplinary fellow in Science and Music at Hambidge, working on tools for visualizing and sonifying dynamical systems for science and art. These “Phase Portraits” are an exploration of the use of time to visualize these systems. The visual style is an ackowledgment of the cyanotype process, which was invented in 1842 by Sir John F. W. Herschel for the intended purpose of reproducing mathematical tables and technical drawings.

Phase Portrait #1 (2025)
Data animation
I talked about the dynamical system depicted above in a previous post (The Statistics of Epidemic Transitions), where I discussed our article in PLOS Computational Biology.
Here, I just want to talk about the animation approach for Phase Portraits and provide a how-to.
The animation uses data from the paper, and renders it using the ggplot2 and gganimate packages in R. The well known ggplot package implements a “Grammar of Graphics” approach to data visualization, focusing on descriptive mappings of data variables to visual variables on the page. Thomas Lin Pedersen’s gganimate extends the grammar to animation, using standard animation vocabulary (“tweening,” “easing,” and the like).
Step by step:
The data: measles.csv
For this animation, I ran the model with a time step of 1 week over 100 years, using six values of the parameter (vaccination level), giving six trajectories. The dataset has columns for week, year, S, I, and a “path” id for the trajectory, as well as the value of used.
Step 1: Load the packages. We load tidyverse (which includes ggplot), plus font and LaTeX utilities for typography. We load ggfx to add visual filters like gaussian blur. The ggpubr and jpeg packages allow us to use a jpeg as a background image. Finally, we load gganimate to give us the animation grammar.
NOTE: Before you start, you must have installed the gifski package. You don’t need to “load” it with library(gifski), but it must be installed in order to render your animation as a gif.
library(tidyverse) # includes ggplot
library(systemfonts) # to access the fonts on your system
library(latex2exp) # to enable LaTeX for beautiful math typography
library(ggfx) # to add visual effects to ggplot plots
library(ggpubr) # to add a background image to ggplot plots
library(jpeg) # to read jpeg images
library(gganimate) # to animate ggplot plots
Step 2: Read in the data, and sort it.
animdata <- read_csv("measles.csv") %>%
arrange(path, year, week)
Step 3: Set up the plot and the main mappings.
For those unfamiliar with ggplot syntax, the mapping argument is how we specify how data variables will be represented graphically. Here, we say map I to the x axis, S to the y axis, and map the path id to color. Now we have a rudimentary ggplot object, which we’ve named theplot.
theplot <- animdata %>%
ggplot(mapping = aes(x=I, y=S, colour = path))
Step 4: Define a color palette to use for paths 1 – 6
thepalette <- c("#2d7db2", "#76afcd", "#f4faf6", "#76afcd", "#2d7db2", "#06538b")
theplot <- theplot + scale_colour_continuous(palette = thepalette)
Step 5: Set up the visual style
Here we define the plot boundaries, then define the visual theme (fonts, color, etc.). We’ll start with a minimal theme that has no unnecessary graphic elements. We’ll customize the theme with our own font family and color.
Then, we’ll some axis labels.
theplot <- theplot +
coord_cartesian(xlim = c(0, .00012), ylim = c(.05, .062)) +
theme_minimal() + # a minimal theme with no extraneous marks
theme(legend.position="none", # hide the legend
text = element_text(family="Hoefler Text", # font family
color = "#06538b"), # text color
axis.text = element_text(colour = "#06538b") # axis text color
) +
labs(x = "Fraction infected (I)", y = "Fraction susceptible (S)")
Preview:
The plot so far
To see what we’ll be animating, let’s preview the plot with the data points. The points are plotted as densely spaced points (using geom_point), not lines.
theplot + geom_point(size = .5)
Step 5: Add the background image
This must be done before we add our data marks, so it doesn’t cover up the data. Leave this step out if you don’t want a background image. We’ll add the points back in afterwards.
bg <- readJPEG("measles.jpg")
theplot <- theplot + background_image(bg)
Step 6: Add the points
For style, we’re going to plot the points twice. First with a bit of gaussian blur, then again on top without. This will make our points glow against the background.
Note: For the animation to work correctly, we need to specify in the mapping that the points should be grouped together by week. This was not needed for the preview, above.
theplot <- theplot +
with_blur(geom_point(size = .5, mapping = aes(group = week)),
sigma = 3 # amount of blur (standard deviation of the gaussian)
) +
geom_point(size = .5, mapping = aes(group = week))
Step 7: Add annotations.
Here’s a bunch of text annotations, accomplished with ggplot’s annotate function. For the mathematical typography, we use LaTex code wrapped in the raw string delimiter r"()" to avoid having to escape special characters. We wrap that in the TeX() function and supply that to the label argument instead of plain text. Skip the annotations if you’re just learning.
annotate("text", .000003, y = .062, color = "#f4faf6", alpha = .75,
family = "Hoefler Text", fontface =2, #bold
label =
'Phase portrait of susceptible and infected populations in a model of measles
transmission, as a function of vaccination level. The portrait illustrates the
phenomenon of "Critical Slowing Down."',
hjust = 0, vjust = 1) +
annotate("text", x = .0001, y = .0605, color = "#f4faf6", alpha = 0.4, family = "Hoefler Text",
label =
"Streamlets are
1 year apart",
hjust = 0, vjust = 1) +
annotate("text", x = .00005, y = .0605, color = "#2d7db2", family = "Hoefler Text",
label = TeX(r"(\nu = 0.90)", output='character'), parse=TRUE) +
annotate("text", x = .0000075, y = .0585, color = "#76afcd", family = "Hoefler Text",
label = TeX(r"(\nu = 0.92)", output='character'), parse=TRUE) +
annotate("text", x = .000004, y = .0578, color = "#f4faf6", family = "Hoefler Text",
label = TeX(r"(\nu = 0.94)", output='character'), parse=TRUE) +
annotate("text", x = .0000025, y = .057, color = "#76afcd", family = "Hoefler Text",
label = TeX(r"(\nu = 0.96)", output='character'), parse=TRUE) +
annotate("text", x = .0000135, y = .055, color = "#06538b", family = "Hoefler Text",
label = TeX(r"(\nu = 0.999)", output='character'), parse=TRUE) +
annotate("text", x = .0001, y = .05, color = "#f4faf6", alpha = .4, family = "Hoefler Text",
label = TeX(r"(Measels virus, \textit{Morbillivirus hominis})",
output='character'),
parse=TRUE, hjust = .5, vjust = 1) +
annotate("text", x = .000027, y = .05675, color = "#f4faf6", alpha = .6, family = "Hoefler Text",
label =
"Below the critical vaccination threshold of 0.941 the system
oscillates, decaying to an equilibrium. Rotation about the
equilibrium becomes slower as vaccination approaches the
critical threshold. Above the threshold, the system decays
to extinction increasingly rapidly as vaccination increases,
without oscillation. The susceptible and infected population
dynamics are given by a system of
differential equations:",
hjust = 0, vjust = 1) +
annotate("text", x = .000027, y = .0532, color = "#f4faf6", alpha = .6, family = "Hoefler Text",
label = TeX(r"($\frac{dS}{dt} = - \beta SI - \eta S + b(1 - \nu) - \mu S$)",
output='character'), parse=TRUE, hjust = 0, vjust = 1) +
annotate("text", x = .000027, y = .0524, color = "#f4faf6", alpha = .6, family = "Hoefler Text",
label = TeX(r"($\frac{dI}{dt} = \beta SI + \eta S - (\gamma + mu I)$)",
output='character'), parse=TRUE, hjust = 0, vjust = 1) +
annotate("text", x = .000012, y = .051, color = "#f4faf6", alpha = .6, family = "Hoefler Text",
label = TeX(r"(Transmission rate $\beta$ depends on vaccination level $\nu$.)",
output='character'), parse=TRUE, hjust = 0, vjust = .5) +
annotate("text", x = .000005, y = .05065, color = "#f4faf6", alpha = .6, family = "Hoefler Text",
label = TeX(r"(Other rates: $b = $ birth, $\mu = $ death, $\gamma = $ recovery, $\eta = $ introduction)",
output='character'), parse=TRUE, hjust = 0, vjust = .5)
Step 8: Animation magic.
Here’s where the magic happens. The animation code is deceptively simple, but relies on all the proper setup we did previously. If the data sorting and mappings are not done carefully, we can get misordered frames or other problems.
We have data with a high temporal resolution (52 weeks 100 years), so we can do frame-by-frame animation without any “tweening” required. gganimate can do tweening, but that’s more appropriate for smooth transitions between a small number of states.
First, we set up the mapping of data to animation frames using the transition_time() function, which is designed for mapping regularly spaced time points to frames. Our animation will consist of 52 frames, one for each week of the year. By setting transition_time(time = week), data (S and I) for week 0 from all years will be shown on frame 1, week 1 on frame 2, etc. This results in multiple points equally spaced at intervals of one year. This is helpful from a data visualization design perspective, because every graphic mark should represent information in some way. Rather than leave visual spacing of points to chance, we make spacing carry extra information.
Next, we create “streamlets” by specifying a shadow for the fames:
shadow_wake(wake_length = 1) means the moving point will leave a wake behind it. shadow_wake lets you control the shape, color, and other parameters of the wake. By default, the wake will create a tail of the same color as the points, that decreases to size=0 and alpha=zero at the tip. We’ll specify the length of the wake as a proportion of the whole animation (52 weeks). wake_length = 0.5 would make the wakes half as long.
theanimation <- theplot %>%
transition_time(time = week) +
shadow_wake(wake_length = 1)
Step 9: Render the animation.
This will take 15 minutes or so.
We will render the animation to a gif, specifying the number of frames (nframes), famerate (fps), width and height in pixels. Duration is nframes fps.
The rendered animation will show in the Rstudio Viewer panel. We can save the animation as a file with anim_save().
animate(
plot = theanimation,
nframes = 52,
fps = 30,
width = 1000, height = 996,
)
anim_save("critical_slowing.gif")