Search code examples
rggplot2gganimate

Keep points in gganimate


I would like to document the progress in a test situation using gganimate: I have come so far:

library(tidyverse)
library(gganimate)

data <- tribble(~user, ~agree, ~accord, ~messung,
            "1", .8, .9, 1,
            "2",.7, .8, 1,
           "3", .6, .9, 1)
data2 <- tribble(~user, ~agree2, ~accord2, ~messung2,
           "1",  .4, .7, 2,
            "2", .5, .9, 2,
            "3", .9, .9, 2)

data%>%
left_join(data2)%>%
 mutate(user = as.numeric(user))%>%
 ggplot(aes(x = accord, y = agree))+
 geom_point(aes(fill = "grey"), color = "grey", size = 2)+
 geom_point(aes(x = accord2, y = agree2), color = "green",
         size = 2)+
 xlim(0,1)+
 ylim(0,1)+
 geom_segment(aes(x = accord,
               y = agree,
               xend = accord2,
               yend = agree2),
           size = 0.5, arrow = arrow(type="closed", length =
                                       unit(.08, "inches"), angle = 30), 
color = "grey")+
theme_minimal()+
guides(fill=FALSE, color=FALSE)+
transition_manual(user)

The colours and representations are of secondary importance at first. It would be important to learn how to animate the points one after the other without the previous points disappearing again? Any help is welcome! Thanks


Solution

  • Maybe just create another dataframe that holds the previous observations, and add it using geom_point:

    ## Your example:
    dat <- data %>%
      left_join(data2) %>%
      mutate(user = as.numeric(user))
    ggplot(dat) +
      geom_point(aes(x = accord, y = agree)) +
      geom_point(aes(x = accord2, y = agree2), color = "green") +
      xlim(0, 1) +
      ylim(0, 1) +
      geom_segment(aes(
        x = accord,
        y = agree,
        xend = accord2,
        yend = agree2
      )) +
      transition_manual(user) -> p
    
    # Now add:
    rows <- unlist(sapply(2:nrow(dat), seq))
    cols <- grep("agree|accord", names(dat), val = T)
    df_points <- dat[rows, cols]
    df_points$user <- rep(dat$user[-1], 2:nrow(dat))
    p +
      geom_point(aes(x = accord, y = agree), df_points) +
      geom_point(aes(x = accord2, y = agree2), df_points, color = "green")
    

    enter image description here