gpt4 book ai didi

r - 在过渡期间增加轮值

转载 作者:行者123 更新时间:2023-12-03 16:39:36 25 4
gpt4 key购买 nike

我想用 gganimate 包创建一个动画条形图。在每个条形的顶部,我想将条形的值四舍五入到零位。

考虑以下示例:

# Example data
df <- data.frame(ordering = c(rep(1:3, 2), 3:1, rep(1:3, 2)),
year = factor(sort(rep(2001:2005, 3))),
value = round(runif(15, 0, 100)),
group = rep(letters[1:3], 5))

# Create animated ggplot
ggp <- ggplot(df, aes(x = ordering, y = value)) +
geom_bar(stat = "identity", aes(fill = group)) +
transition_states(year, transition_length = 2, state_length = 0) +
geom_text(y = df$value, label = as.integer(round(df$value)))
ggp

enter image description here

不幸的是,我没有设法正确地舍入这些值。有没有办法在转换期间舍入值?

最佳答案

由于 df$value 已经通过 round() 四舍五入为零小数,因此您可以在设置标签时使用 as.character() 。

> df$value
[1] 29 81 92 50 43 73 40 41 69 15 11 66 4 69 78
> as.character(df$value)
[1] "29" "81" "92" "50" "43" "73" "40" "41" "69" "15" "11" "66" "4" "69" "78"

结果:
ggp <- ggplot(df, aes(x = ordering, y = value)) +
geom_bar(stat = "identity", aes(fill = group)) +
transition_states(year, transition_length = 2, state_length = 0) +
geom_text(label = as.character(df$value))

enter image description here

关于r - 在过渡期间增加轮值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616746/

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