帧之间的gganimate变化轴

Jam*_*rus 2 r ggplot2 gganimate

我正在尝试使用 gganimate 绘制 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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

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

kik*_*ton 5

我将这篇文章中的解决方案改编为您的示例。我还稍微更改了数据,以便我们可以看到第 3 个玩家退出,另一个玩家进入。该gganimate网站也是看一些例子的好地方。

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

一个观察:你必须使用group里面的审美geom_col。我认为这说明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
Run Code Online (Sandbox Code Playgroud)

这是结果:

在此处输入图片说明