gganimate 在帧之间更改轴

gganimate change axes between frames

我正在尝试使用 gganimate 随着时间的推移绘制前 3 名 NHL 得分手。目前,我有一个柱形图,其中 x 轴显示球员姓名,y 轴显示每个球员的进球数。这是我所拥有的静态版本:

library(ggplot2)

data <- data.frame(name=c("John","Paul","George","Ringo","Pete","John","Paul","George","Ringo","Pete"),
     year = c("1997", "1997", "1997", "1997", "1997", "1998", "1998","1998","1998", "1998"),
     goals = c(50L, 35L, 29L, 5L, 3L, 3L, 5L, 29L, 36L, 51L))

data <- data %>%
  arrange(goals) %>%
  group_by(year) %>%
  top_n(3, goals)

ggplot(data, 
  aes(x = reorder(name, goals), y=goals)) +
  geom_col() +
  facet_wrap(data$year) +
  coord_flip()

我想要的是只显示前 3 名玩家。换句话说,当年进入前三但第二年跌出前三的球员不应该出现在第二帧上。最终产品应如下所示:

https://www.youtube.com/watch?v=nYjpZcPhoqU

我改编了来自 this post to your example. I also changed the data a little bit so we could see the 3rd player dropping out and another one entering in its place. The gganimate website 的解决方案也是查看一些示例的好地方。

诀窍是使用排名作为您的 x 轴(或翻转图中的 y 轴)。这样,当排名从一年更改为另一年时,列的位置也会发生变化。然后您可以隐藏 x 轴的标签并在所需位置(在本例中为 x 轴)创建一个带有 geom_text 的文本标签。

一个观察:你必须在 geom_col 中使用 group 美学。我认为这告诉 gganimate 某些形状在帧之间是相同的(因此它们相应地移动)。

这是我的代码:

library(ggplot2)
library(gganimate)
library(plyr)
library(dplyr)
library(glue)

# I changed your data set a little
data <- data.frame(name=c("John","Paul","George","Ringo","Pete",
                          "John","Paul","George","Ringo","Pete"),
                   year = c("1997", "1997", "1997", "1997", "1997", 
                            "1998", "1998","1998","1998", "1998"),
                   goals = c(50L, 35L, 29L, 5L, 3L, 
                             45L, 50L, 10L, 36L, 3L))

# create variable with rankings (this will be used as the x-axis) and filter top 3
data2 <- data %>% group_by(year) %>%
  mutate(rank = rank(goals)) %>% filter(rank >= 3)

stat.plot <- ggplot(data2) +
  # **group=name** is very important
  geom_col(aes(x=rank, y=goals, group=name), width=0.4) +
  # create text annotations with names of each player (this will be our y axis values)
  geom_text(aes(x=rank, y=0, label=name, group=name), hjust=1.25) +
  theme_minimal() + ylab('Goals') +
  # erase rank values from y axis
  # also, add space to the left to fit geom_text with names
  theme(axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        plot.margin = unit(c(1,1,1,2), 'lines')) +
  coord_flip(clip='off')

# take a look at the facet before animating
stat.plot + facet_grid(cols=vars(year))

# create animation
anim.plot <- stat.plot + ggtitle('{closest_state}') + 
  transition_states(year, transition_length = 1, state_length = 1) +
  exit_fly(x_loc = 0, y_loc = 0) + enter_fly(x_loc = 0, y_loc = 0)

anim.plot

这是结果: