如何在ggplot动画中让NBA球队数据的均值线随年份动态更新?
Hey there, the issue here is that your current geom_hline and geom_vline are calculating the overall mean across the entire dataset, not the mean for each individual year. That's why the lines stay fixed instead of updating with each frame of your animation.
Here's how to fix it:
First, pre-calculate the average assist rate and 3-point attempt rate for each year. We'll use dplyr to group the data by season year and compute the means:
# Load dplyr if you haven't already library(dplyr) # Calculate yearly averages yearly_means <- dataBREFPerPossTeams %>% group_by(yearSeason) %>% summarize( avg_ast = mean(astPerPossTeam), avg_fg3a = mean(fg3aPerPossTeam) )
Next, modify your ggplot to use this yearly summary data for the mean lines. We'll split the plot layers: one for the team data points, and another for the year-specific mean lines:
# Build the base plot p <- ggplot() + # Team data points (original layer) geom_point(data = dataBREFPerPossTeams, aes(astPerPossTeam, fg3aPerPossTeam, col = ptsPerPossTeam)) + 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") + # Year-specific horizontal mean line (3PA per 100 poss) geom_hline(data = yearly_means, aes(yintercept = avg_fg3a), color='blue', linetype='dashed') + # Year-specific vertical mean line (Assists per 100 poss) geom_vline(data = yearly_means, aes(xintercept = avg_ast), color='blue', linetype='dashed') # Add animation transition anim <- p + transition_time(as.integer(yearSeason)) + labs(title='Year: {frame_time}') # Render the animation animate(anim, nframes=300)
Why this works:
By creating a separate summary dataset (yearly_means) that holds the mean values for each year, we're telling gganimate to pull the correct mean for each frame's year. The original code used the full dataset's mean, which never changes—this approach ensures each frame uses the mean specific to that season.
Just make sure yearSeason is formatted consistently (your use of as.integer(yearSeason) is perfect for this) so the animation syncs correctly between the team points and the mean lines.
内容的提问来源于stack exchange,提问作者Jack Renshaw-Lewis

