Search code examples
rggplot2gganimate

R gganimate iterate through which group is emphasized by color, size, alpha


> head(data8)
# A tibble: 6 x 8
  name                industry           Time  evToGi evToRev  size alpha color  
  <chr>               <chr>              <chr>  <dbl>   <dbl> <dbl> <dbl> <chr>  
1 Activision Blizzard Gaming             Dec18   5.93    2.73     6   0.1 #777777
2 Activision Blizzard Gaming             Jun15   8.17    5.23     4   0.1 #777777
3 Adobe               Software Solutions Dec18   6.87    4.33     6   0.1 #777777
4 Adobe               Software Solutions Jun15   5.69    3.81     4   0.1 #777777
5 Amazon              Ecommerce          Dec18  39.8     6.77     6   1   #0066CC
6 Amazon              Ecommerce          Jun15  12.7     2.28     4   1   #0066CC

data8 %>%
  ggplot(aes(x = evToRev, y = evToGi, colour = industry)) +
  geom_line(aes(group = name), alpha = data8$alpha, colour = "#666666") +
  geom_point(
    size = data8$size,
    alpha = data8$alpha,
    color = data8$color) +
  labs(x = 'EV/R', y = 'EV/GM', 
       title = 'Change in EV/R and EV/GM multiples for ECommerce tech giants, 2015 - 2018')

enter image description here Hi all,

I have the following data and graph created using ggplot, and I would like to animate through each of the 10 different industries, emphasizing each industry at a time via a size, color and alpha, while the other 9 industries are greyed out.

This is a bit different than the example in the docs here, where each iris group is showed at a time. In my example, I'd like all of the data to always show, and to simply iterate by changing which industry is focused on.

Any thoughts on how to do this using gganimate? I am working on this currently and will update the post with any progress made.

Edit: I assume this will involve some refactoring as I won't be able to hardcode the size, alpha, and color in the manner than I am currently doing so...


Solution

  • I tested this out quickly, and it doesn't work exactly as you mentioned. Hopefully it's enough to start you in the right direction.

    industries <- unique(data8$industry) %>% paste(collapse = ",")
    
    data8 <- data8 %>% 
      mutate(ind = industries) %>% 
      separate_rows(., ind, sep = ",") %>% 
      mutate(color = ifelse(ind == industry, "#0066CC", "#777777"),
         alpha = ifelse(ind == industry, 1, .1))
    
    p <- ggplot(data8, aes(x = evToRev, y = evToGi, colour = industry)) +
      geom_line(aes(group = name, alpha = alpha), colour = "#666666") +
      geom_point(aes(alpha = alpha,
             color = color),
      size = data8$size,
      ) +
    scale_alpha_identity() +
    scale_color_identity() +
    labs(x = 'EV/R', y = 'EV/GM', 
        title = 'Change in EV/R and EV/GM multiples for ECommerce tech giants, 2015 - 2018') 
    
    anim <- p + transition_states(ind)
    
    anim