最后一个图中的动画条形图错误(gganimate)?

Animate bar chart error in last plot (gganimate)?

我创建了一个动画条形图,但标签值不正确。我不知道为什么 cum_2 在我的数据中是一个整数,但在生成的 gif 中,标签文本显示为实数(例如:674.5... 而不是 675)。

library(tidyverse)
library(gganimate)
df <- data.frame(date = c(rep('2020-07-08',4), rep('2020-07-09',4), 
                       rep('2020-07-10',4), rep('2020-07-11',4),
                       rep('2020-07-12',4)),
              sub = rep(c("PYTHON", "SQL", "VBA", "R"),5),
              cum_2 =  c(659,609,454,450,659,609,468,450,670,609,478,450,670, 609,486,461,679,609,486,469),
              rank = rep(c(1,2,3,4),5))

fill <- c('red','blue','green','orange')  # example fill colors

df %>% 
  ggplot(aes(rank, y = cum_2, 
             fill = sub)) +
  geom_col(alpha = 0.6)+
  scale_fill_manual(values = fill) +
  geom_text(aes(y = 0, 
                label = paste(sub, " ")), 
            vjust = 0.2, 
            hjust = 1) +
  transition_states(states = date,transition_length = 4, state_length = 1)  +
  geom_text(aes(y = cum_2,
                label = round(cum_2,0), 
                hjust = 0,
                size = 12)) +
  scale_x_reverse() +
  coord_flip(clip = "off", expand = FALSE) +
  guides(color = FALSE, fill = FALSE) +
  theme(axis.line=element_blank(),
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank(),
        legend.position="none",
        panel.background=element_blank(),
        panel.border=element_blank(),
        panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        panel.grid.major.x = element_line( size=.1, color="grey" ),
        panel.grid.minor.x = element_line( size=.1, color="grey" ),
        plot.title=element_text(size=25, hjust=0.5, face="bold", colour="grey", vjust=-1),
        plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="grey"),
        plot.caption =element_text(size=8, hjust=0.5, face="italic", color="grey"),
        plot.background=element_blank(),
        plot.margin = margin(2,2, 2, 4, "cm")) +
  labs(title = 'MCI Vietnam : {closest_state}',  
       subtitle  =  "Number of students") +
  view_follow(fixed_x = TRUE) +
  enter_fade() +
  exit_shrink() +
  ease_aes('sine-in-out') -> anim

# gif
animate(anim, nframes = length(unique(df$date)), 
        detail = 5,
        fps = 5,
        # duration = 20,
        renderer = gifski_renderer("file.gif"))

这里是 gif 文件中的最后一个情节:

感谢大家阅读和支持我。

由于条形的 y 位置在动画中进行了补间(cum_2 在您的数据框中),并且标签位置和文本基于 cum_2,它也会进行补间和结果是你有很多小数位的数字作为结果出现。

幸运的是,修复非常简单:只需强制对您的标签进行评估 as.character()。将您的 geom_text 行更改为如下内容,这样就解决了问题:

  geom_text(aes(y = cum_2, label = as.character(round(cum_2,0)), 
                hjust = 0, size = 12))

这是结果(用 duration=5 保存):

*仅供参考:您的代码缺少您使用的颜色,所以我在这里定义了 fill=c('red','blue','green','orange')