R语言gganimate包transition_reveal()未遵循x轴排序问题求助
核心问题原因
transition_reveal() 函数是按照传入参数的数值从小到大顺序逐步展示画面,你之前传入的是载客量stop_charge,这个值在有轨电车线路后半段会逐渐下降,导致动画不会按照站点顺序推进,反而会跳回前面的位置。
解决方法
仅需调整两处代码即可:
- 保留数据中的站点顺序字段
stop_order,该字段本身是单调递增的,完全匹配站点的运行顺序 - 将
transition_reveal()的参数替换为stop_order
修正后的完整代码如下:
library(tidyr) library(dplyr) library(ggplot2) library(gganimate) tramway_df <- data.frame( stop_order = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17), stop_id = c(9943, 5041, 5361, 2902, 2903, 5872, 5802, 5803, 5804, 5805, 5710, 5711, 5712, 1643, 5714, 521, 529), stop_name = c("DA VINCI", "DA VINCI", "BORDET STATION", "VAN CUTSEM", "FONSON", "PAIX", "TILLEUL", "HELMET", "FOYER SCHAERBEEK.", "WAELHEM", "VERBOEKHOVEN", "PAVILLON", "RUBENS", "LIEDTS", "THOMAS", "GARE DU NORD", "ROGIER"), stop_in = c(27, 102, 153, 141, 190, 317, 379, 438, 328, 214, 278, 298, 154, 144, 162, 185, 0), stop_out = c(0, 7, 3, 10, 22, 37, 81, 122, 143, 168, 291, 230, 149, 301, 412, 707, 821), stop_charge = c(27, 121, 271, 402, 571, 851, 1149, 1465, 1650, 1696, 1682, 1745, 1750, 1592, 1342, 821, 0) ) tramway_df %>% gather(movement, value, stop_in:stop_out) %>% # 用stop_order重排stop_id的因子顺序,避免原数据行序错乱导致x轴顺序错误 mutate(stop_id = reorder(stop_id, stop_order)) %>% ggplot(aes(x=stop_id)) + geom_col(aes(y=value, fill = movement), position = "dodge", width = 1) + geom_line(aes(y=stop_charge, group=1)) + scale_x_discrete(breaks = tramway_df$stop_id, labels = tramway_df$stop_name) + # 替换为站点顺序字段,动画就会沿站点顺序推进 transition_reveal(stop_order)
如果需要调整动画速度,可以在代码末尾加上animate(duration = 10, nframes = 100),自行调整总时长和总帧数即可。
内容的提问来源于stack exchange,提问作者salwa
相关产品推荐
相关产品推荐

