Skip to content

Instantly share code, notes, and snippets.

@noamross
Last active May 14, 2022 03:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noamross/5a648649a8f0a3c35e7b18da419ac8c7 to your computer and use it in GitHub Desktop.
Save noamross/5a648649a8f0a3c35e7b18da419ac8c7 to your computer and use it in GitHub Desktop.
Animating vertices of a graph with gganimate and ggraph
library(tidyverse)
library(igraph)
library(ggraph)
library(gganimate)
library(ggforce)
#File at https://dl.dropbox.com/s/hxmsut19lelgw33/epinetwork.rds
episim <- readRDS("epinetwork.rds") # Saved is the simulation data and an adjacency matrix for the network
# Create an undirected graph from this matrix
ign <- graph_from_adjacency_matrix(episim$network > 0, "undirected")
# Create a layout from the network, attach the x/y values to the simulation data
set.seed(1)
layout <- layout_with_fr(ign) %>% as.data.frame() %>% rename(x=V1, y=V2)
sim1 = episim$simulation %>%
group_by(time) %>%
mutate(x =layout$x, y=layout$y) %>%
group_by()
sim_end = filter(sim1, time==100) # A single time point for use for background
plot <- ggraph(ign, 'manual', node.positions=layout) +
geom_edge_arc(curvature = 0.1, edge_colour='grey40') +
geom_node_point(data=sim_end, mapping=aes(x=x, y=y), #white bg for the nodes
shape=21, size=5, stroke=1, #to hide the edges beind
color="white", fill="white") + #them
geom_node_point(data=sim1,
mapping=aes(x=x, y=y, fill= (I > 0), alpha=S, frame=time),
shape=21, size=5, stroke=1, color="grey10") +
scale_fill_manual(breaks=c(0, 1), values=c("black", "red")) +
scale_alpha_continuous(range=c(0,1)) +
ggforce::theme_no_axes() +
theme(legend.position="none",
panel.border = element_blank())
animation::ani.options(interval=0.1)
gg_animate(plot, 'epi_animation.gif', title_frame = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment