GGanimate:具有数值的geom_text设置为十进制数字而不是整数

时间:2018-10-29 22:59:25

标签: r ggplot2 gganimate

Data <- data.frame(Time = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                   Group = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
                   Value = c(20, 10, 15, 20, 20, 20, 30, 25, 35))

我在Time中的三个不同点上有三个具有值的组。

library(ggplot2)
library(gganimate)

p <- ggplot(Data, aes(Group, Value)) +
     geom_col(position = "identity") +
  geom_text(aes(label = Value), vjust = -1) +
     coord_cartesian(ylim = c(0, 40)) +
     transition_time(Time)
p 

上面的代码很好地产生了用于条形转换的动画,但是geom_text的更改仍然有很多不足之处,因为geom_text补间/过渡的小数位数大于10。理想情况下,我希望geom_text数值在过渡时保持为整数,或者通过某种方式来控制舍入程度。

编辑:将Value更改为整数类型无济于事。

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以尝试自行计算转换...

library(gganimate)
library(tidyverse)
Data2 <- Data %>% 
  group_by(Group) %>% 
    arrange(Group) %>% 
    mutate(diff = c((Value - lag(Value))[-1],0))

Seq <- seq(1,3,0.01)
library(gganimate)
tibble(Time_new=rep(Seq,3), Group = rep(LETTERS[1:3], each = length(Seq))) %>% 
  mutate(Time=as.numeric(str_sub(as.character(Time_new),1,1))) %>% 
  left_join(Data2)  %>%
  group_by(Group, Time) %>% 
  mutate(diff = cumsum(diff/n())) %>% 
  mutate(Value2 = Value + diff) %>%
  mutate(new_old = ifelse(Time == Time_new, 2, 1)) %>% 
  ggplot(aes(Group, Value2)) +
  geom_col(position = "identity") +
  geom_text(aes(label = sprintf("%1.2f",Value2)), vjust = -1) +
  coord_cartesian(ylim = c(0, 40)) +
  transition_manual(Time_new) 

enter image description here

或尝试geom_text(aes(label = round(Value2,2)), vjust = -1)

答案 1 :(得分:1)

软件包作者提供了一个非常优雅的通用解决方案,

..只需将"Year: {as.integer(frame_time)}"作为标题

来自here