November 30, 2025

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 ν\nu (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 ν\nu 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 farThe 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 ×\times 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 ×\times 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")
November 1, 2019

Turbulence at FLUX Ponce City Market

TurbulenceTurbulence

In September, my collective Otherpole (Kai Riedl and I) put on a large scale interactive spatial sound installation, Turbulence under the Beltline Shed at Ponce City Market in Atlanta, Georgia, as part of FLUX: Ponce City Market, curated by Ben Coleman.

From Sep 26–29, we turned the Shed into an immersive spatial sonic environment, exploring the superposition of environments — natural and industrial, real and simulated, present and past. Virtual bird flocks algorithmically reconstructed from field recordings flew the length of the Shed, interacting, and hybridizing with the past and present industrial and human soundscapes of Ponce City Market and the BeltLine. Audience members were able to steer flocks through space using a touch interface.

Then we invited electronic musicians to come perform with us and spatialized their live feeds in real time. Performers included Duet for Theremin and Lapsteel, TRIPLE X SNAXXX, No Eyes, Kil Christenson, Ultrabillions, Deantoni Parks, and Bana Haffar.

Meyer Sound generously provided the multichannel speaker array for Turbulence.

Read Mark Gresham’s review in EarRelevant here: https://www.earrelevant.net/2019/10/review-flux-projects-sounds-out-ponce-city-market/

May 22, 2019

Project Tycho 2.0 R interface

The tycho2 R package is here! https://github.com/allopole/tycho2

I wrote a small R package to provide an R interface for data from Project Tycho 2.0, a repository for global health data in a standardized format compliant with FAIR (Findable, Accessible, Interoperable, and Reusable) guidelines.

Version 2.0 of the database currently contains:

  • weekly case counts for 78 notifiable conditions for 50 states and 1284 cities between 1888 and 2014, reported by health agencies in the United States;
  • data for dengue-related conditions for 100 countries between 1955 and 2010, obtained from the World Health Organization and national health agencies.

After installing tycho2 from github and creating an account with Project Tycho, this is all you need to do in R to retrieve data:

# Get all measles cases in California from 2000 to 2010
# Note: Retrieve your API key from your Project Tycho account

queryterms <- c(
  "ConditionName=Measles",
  "Admin1ISO=US-CA",
  "PeriodStartDate>=2000-01-01",
  "PeriodEndDate<=2010-01-01"
  )
  
Measles_CA_2000_2010 <- tycho2("query", 
                               queryterms=queryterms,
                               apikey='some1long2alphanumeric3string')

That’s it.

The development of this package was supported by the National Institute of General Medical Sciences of the National Institutes of Health under Award Number U01GM110744. The content is solely the responsibility of the authors and does not necessarily reflect the official views of the National Institutes of Health.

May 16, 2019

The Statistics of Epidemic Transitions

I recently joined Project AERO (Anticipating Emerging and Re-emerging Outbreaks), a collaboration involving researchers at the Universities of Georgia, Michigan, and Penn State developing new methods for forecasting emergence and re-emergence of infectious diseases based on the theory of critical slowing down.

Our new paper in PLOS Computational Biology, The Statistics of Epidemic Transitions, explains the connection between epidemics and damped harmonic oscillators.

Critical slowing down illustrated in the potential function of a linearized SIR (“Susceptible-Infected-Recovered”) model of disease transmission with vaccination. Disease prevalence (I/N) is represented by the horizontal position of a ball sliding through viscous fluid in a well having a height determined by the potential function. Both the depth of the well and the viscosity of the fluid in the equivalent physical system are affected by vaccine coverage. The well is shallowest near the immunization threshold, which illustrates the slowing down of the dynamics as the critical point ν ≈ 0.941 (green dashed line) is approached. Oscillatory dynamics occur at another immunization level ν ≈ 0.939 corresponding to the system becoming underdamped (pink region). To write the potential function in terms of prevalence, we scaled the deviations of the linearized system by the square root of the equilibrium population size. Critical slowing down is seen in this figure in the relative magnitude of the displacement of the ball with respect to the distance from the critical level of immunization.

In lay terms, the idea (pointed out by by co-author Eamon O’Dea) is that in a population with an infectious disease going around, the number of infected people will oscillate over time around an equilibrium point. Mathematically, this oscillation can be described approximately by the same equations that described a “damped harmonic oscillator,” like a pendulum, or a bell, or a violin string.

The above figure is my attempt to depict what happens when you gradually “dampen” the oscillations (by applying increasing friction to the pendulum or vaccinating the public). Above a critical threshold of dampening, the oscillations die out completely. But before that threshold, the oscillations slow down, taking longer to complete a cycle. In principle, we should be able to use this “critical slowing down” in the oscillations to predict an approaching threshold in real data (like disease case reports).

Here’s another way to see the oscillations. This time, we see them a spirals in “phase space”, with infected people on the x axis and susceptible people on the y. The big red and black dots are just starting points. The oscillations eventually decay to a point on the blue line. Where on the blue line the spirals end depends only on the vaccination level. Above the critical threshold of vaccination, the paths cease to spiral and just decay directly to the blue line. Time on this plot is represented by the spacing of individual dots.

Dynamics of deterministic component of SIR model as a function of vaccine uptake. The motion becomes slower as the vaccine uptake approaches the threshold.

November 1, 2018

New installation at Human and the Machine

Human and the MachineHuman and the Machine

My new audio installation Loci will be up at the Georgia Theatre in Athens Georgia, Saturday, November 3, 2018. Loci is part of “Human and the Machine”, a one day event presented by Moogfest, with Kishi Bashi, Tall Tall Trees, Deantoni Parks, Lauren Sarah Hayes, and audiovisual work by REM’s Michael Stipe.

Human and the Machine is presented in conjunction with a2ru.

Meyer Sound has generouasly provided the multichannel speaker array for Loci.


© Copyright 2015 Éric Marty