gpt4 book ai didi

r - GGanimate:具有数值的 geom_text 以十进制数字而不是整数进行动画

转载 作者:行者123 更新时间:2023-12-02 11:39:18 25 4
gpt4 key购买 nike

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))

我有三个组,其值位于时间的三个不同点。

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

最佳答案

您可以尝试预先计算自己的转换...

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)

关于r - GGanimate:具有数值的 geom_text 以十进制数字而不是整数进行动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53055118/

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