2

I am trying to develop an animated plot showing how the rates of three point attempts and assists have changed for NBA teams over time. While the points in my plot are transitioning correctly, I tried to add a vertical and horizontal mean line, however this is staying constant for the overall averages rather than shifting year by year.

p<-ggplot(dataBREFPerPossTeams, aes(astPerPossTeam,fg3aPerPossTeam,col=ptsPerPossTeam))+
  geom_point()+
  scale_color_gradient(low='yellow',high='red')+
  theme_classic()+
  xlab("Assists Per 100 Possessions")+
  ylab("Threes Attempted Per 100 Possessions")+labs(color="Points Per 100 Possessions")+
  geom_hline(aes(yintercept = mean(fg3aPerPossTeam)), color='blue',linetype='dashed')+
  geom_vline(aes(xintercept = mean(astPerPossTeam)), color='blue',linetype='dashed')

anim<-p+transition_time(as.integer(yearSeason))+labs(title='Year: {frame_time}')

animate(anim, nframes=300)

Example of GIF

Ideally, the two dashed lines would shift as the years progress, however, right now they are staying constant. Any ideas on how to fix this?

M--
  • 25,431
  • 8
  • 61
  • 93

1 Answers1

4

I am using datasets::airquality since you have not shared your data. The idea here is that you need to have the values for your other geom (here it is mean) as a variable in your dataset, so gganimate can draw the connection between the values and frame (i.e. transition_time).

So What I did was grouping by frame (here it is month and it will be yearSeason for you) and then mutating a column with the average of my desired variables. Then in geoms I used that appended variable instead of getting the mean inside of the geom. Look below;

library(datasets) #datasets::airquality

library(ggplot2)
library(gganimate)
library(dplyr)

g <- airquality %>% 
             group_by(Month) %>% 
             mutate(mean_wind=mean(Wind),
                    mean_temp=mean(Temp)) %>% 
        ggplot()+
          geom_point(aes(Wind,Temp, col= Solar.R))+
          geom_hline(aes(yintercept = mean_temp), color='blue',linetype='dashed')+
          geom_vline(aes(xintercept = mean_wind), color='green',linetype='dashed')+
          scale_color_gradient(low='yellow',high='red')+
          theme_classic()+
          xlab("Wind")+
          ylab("Temp")+labs(color="Solar.R")

animated_g <- g + transition_time(as.integer(Month))+labs(title='Month: {frame_time}')

animate(animated_g, nframes=18)

Created on 2019-06-09 by the reprex package (v0.3.0)

M--
  • 25,431
  • 8
  • 61
  • 93