gpt4 book ai didi

r - gganimate 在帧之间更改轴

转载 作者:行者123 更新时间:2023-12-02 19:49:36 27 4
gpt4 key购买 nike

我正在尝试使用 gganimate 绘制一段时间内 NHL 前 3 名得分手的图。目前,我有一个柱形图,其中 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

最佳答案

我改编自 this post 的解决方案以你为例。我还稍微更改了数据,这样我们就可以看到第三名玩家退出,另一名玩家进入其位置。 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

这就是结果:

enter image description here

关于r - gganimate 在帧之间更改轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58507077/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com