首页 > 解决方案 > gganimate 在帧之间更改轴

问题描述

我正在尝试使用 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

标签: rggplot2gganimate

解决方案


我将这篇文章中的解决方案改编为您的示例。我还稍微更改了数据,以便我们可以看到第三个玩家退出,另一个玩家进入。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

这是结果:

在此处输入图像描述


推荐阅读