改变帧之间的坐标轴

时间:2019-10-22 14:57:58

标签: r ggplot2 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()

enter image description here

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

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

1 个答案:

答案 0 :(得分:3)

我将解决方案从this post修改为您的示例。我还稍微修改了数据,所以我们可以看到第3个播放器退出了,另一个播放器进入了它的位置。 gganimate website也是查看某些示例的好地方。

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

一个观察结果:您必须在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

这是结果:

enter image description here