我创建了一个动画条形图,显示了一些玩家的得分目标。在整个代码下方显示我是如何进入输出的。
动画像希望的那样运作。但是,有相同的酒吧……
的 基于澄清的编辑解决方案 强> :
gap %>% # for each player, note his the rank from his previous day group_by(Player) %>% arrange(Gameday) %>% mutate(prev.rank = lag(rank)) %>% ungroup() %>% # for every game day, # sort players by rank & break ties by previous day's rank group_by(Gameday) %>% arrange(rank, prev.rank) %>% mutate(x = seq(1, n())) %>% ungroup() %>% ggplot(aes(x = x, y = Goals, fill = Player, color = Player)) + # geom_tile(aes(y = Goals/2, height = Goals, width = width)) + geom_col() + geom_text(aes(y = 0, label = Player), hjust = 1) + geom_text(aes(label = Value_lbl), hjust = 0) + # rest of the code below is unchanged from the question coord_flip(clip = "off", expand = FALSE) + scale_y_continuous(labels = scales::comma) + scale_x_reverse() + guides(color = FALSE, fill = FALSE) + labs(title = "Gameday {closest_state}", x="", y = "Goals scored") + theme(plot.title = element_text(hjust = 0, size = 22), axis.ticks.y = element_blank(), axis.text.y = element_blank(), plot.margin = margin(1,1,1,4, "cm")) + transition_states(Gameday, transition_length = 4, state_length = 1) + ease_aes('cubic-in-out')
的 原始解决方案 强> :
gap %>% # for each player, note his the rank from his previous day group_by(Player) %>% arrange(Gameday) %>% mutate(prev.rank = lag(rank)) %>% ungroup() %>% # for every game day & every rank, # reduce tile width if there are multiple players sharing that rank, # sort players in order of who reached that rank first, # & calculate the appropriate tile midpoint depending on how many players are there group_by(Gameday, rank) %>% mutate(n = n_distinct(Player)) %>% mutate(width = 0.9 / n_distinct(Player)) %>% arrange(prev.rank) %>% mutate(x = rank + 0.9 * (seq(1, 2 * n() - 1, by = 2) / 2 / n() - 0.5)) %>% ungroup() %>% ggplot(aes(x = x, fill = Player, color = Player)) + geom_tile(aes(y = Goals/2, height = Goals, width = width)) + geom_text(aes(y = 0, label = Player), hjust = 1) + geom_text(aes(y = Goals, label = Value_lbl), hjust = 0) + # rest of the code below is unchanged from the question coord_flip(clip = "off", expand = FALSE) + scale_y_continuous(labels = scales::comma) + scale_x_reverse() + guides(color = FALSE, fill = FALSE) + labs(title = "Gameday {closest_state}", x="", y = "Goals scored") + theme(plot.title = element_text(hjust = 0, size = 22), axis.ticks.y = element_blank(), axis.text.y = element_blank(), plot.margin = margin(1,1,1,4, "cm")) + transition_states(Gameday, transition_length = 4, state_length = 1) + ease_aes('cubic-in-out')
注意:这并不完美。我想如果有太多玩家/太多天,那么在同一天/等级内确定玩家顺序的上述简单逻辑将是不理想的,因为它只会向后看 的 一 强> 天。但它适用于这个例子,&我对足球知之甚少(至少我 认为 这是足球?)来推断你的用例。