Animated dotplot (using gganimate in R)

I have a data frame of countries and some events in each country. How to animate a dotplot of events for each country through time

df <- data.frame(country = factor(c("Mexico", "USA","France", "USA","France","Mexico", "USA")),
                 start_date =as.Date(c("2016-01-26", "2016-02-26","2016-03-26","2016-04-26","2016-05-26","2016-04-26","2016-05-26")),
                 events = factor(c("Protest", "Election","Covid","Protest", "Election","Protest", "Election"))
                  )

here is my code:

p1 <- ggplot(df, mapping = aes(x=country))+
         geom_dotplot()
p1

I have a data frame of countries and some events in each country. How to animate a dotplot of events for each country through time

df <- data.frame(country = factor(c("Mexico", "USA","France", "USA","France","Mexico", "USA")),
                 start_date =as.Date(c("2016-01-26", "2016-02-26","2016-03-26","2016-04-26","2016-05-26","2016-04-26","2016-05-26")),
                 events = factor(c("Protest", "Election","Covid","Protest", "Election","Protest", "Election"))
                  )

here is my code:

p1 <- ggplot(df, mapping = aes(x=country))+
         geom_dotplot()
p1

I want to animate it over the time

p_anim <- p1 + transition_time(start_date) +
  transition_layers(keep_layers = FALSE) +
  transition_reveal(start_date)+
  ease_aes("linear") +
  enter_fade() +
  exit_fade()
animate(p_anim) 

It only puts the dots on the x-axis and doesn't stack them. What is the solution? Thanks

Hi @Donya,
Welcome to the RStudio Community Forum.

I'm not exactly clear from your question what your desired output is, however, this code produces an animated scatter plot over time of the country x event occurrences:

library(ggplot2)
library(gganimate)

df <- data.frame(country = factor(c("Mexico", "USA","France", "USA","France","Mexico", "USA")),
                 start_date =as.Date(c("2016-01-26", "2016-02-26","2016-03-26","2016-04-26","2016-05-26","2016-04-26","2016-05-26")),
                 events = factor(c("Protest", "Election","Covid","Protest", "Election","Protest", "Election")))
df
str(df)

p1 <- ggplot(df, mapping = aes(x=country, y=events))+
         geom_point(cex=3, colour="red")
p1

# I want to animate it over the time
p_anim <- p1 + transition_time(start_date) +
  transition_layers(keep_layers = FALSE) +
  transition_reveal(start_date)+
  ease_aes("linear") +
  enter_fade() +
  exit_fade()

animate(p_anim) 

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.