【发布时间】:2020-01-21 07:06:33
【问题描述】:
我在为堆叠的静态图设置动画时遇到问题。 (见下方动画)
动画从左到右以不稳定的方式移动,而不是每个条从 x 轴向上增长。堆叠在一起的部分也不会很顺利地生长,我似乎无法解决。
我需要在我的代码中进行哪些更改,以便当动画图沿 x 轴过渡时,各个条形会向上增长?我还想让堆叠的条更平滑地增长,因此堆叠的条部分不会“扔”在彼此的顶部。
这怎么可能?
本文顶部的 gif 是我正在寻找的,但我不明白他的代码与我的代码有何不同以及在哪里:ideal animation
这是我的代表:
#Static df
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
year <- as.numeric(c(1996:2015,
1996:2015,
1996:2015))
c <- c(39, 40, 67, 80, 30, 140, 90, 23, 100, 123,
140, 160, 100, 89, 173, 200, 32, 90, 100, 211,
1, 2, 1, 13, 3, 3, 30, 1, 3, 3,
1, 1, 20, 2, 1, 10, 1, 2, 1, 1,
1, 3, 1, 2, 1, 3, 1, 3, 6, 1,
1, 30, 1, 1, 8, 9, 1, 32, 1, 1)
cat <- as.character(c("out", "out", "out", "out", "out", "out", "out", "out", "out", "out",
"out", "out", "out", "out", "out", "out", "out", "out", "out", "out",
"in", "in", "in", "in", "in", "out", "in", "in", "in", "in",
"in", "in", "in", "in", "in", "in", "in", "in", "in", "in",
"other", "other", "other", "other", "other", "other", "other", "other", "other", "other",
"other", "other", "other", "other", "other", "other", "other", "other", "other", "other"))
cat <- as.factor(cat)
static_df_test <- data.frame(year, c, cat) %>%
select(year, cat, c) %>%
arrange(year, cat)
#Static plot
library(ggplot2)
(static_plot <- ggplot(static_df_test) +
geom_bar(data = static_df_test, stat="identity", position ="stack",
aes(x = year, y = c, fill = cat)) +
scale_x_continuous(breaks = seq(1996, 2015, 1),
expand = c(0.003, 0.003),
labels = c(1996, 97, 98, 99, 2000,
"01", "02", "03", "04", "05", "06",
"07", "08", "09", 10, 11, 12, 13, 14, 15)) +
scale_y_continuous(breaks = seq(0, 250, 25),
expand = c(0,0),
limits = c(0,250)) +
labs(x = "year", y = "c")
)
#Animated plot
library(gganimate)
library(ggplot2)
ani <- (static_plot) +
transition_time(as.integer(year)) +
enter_grow() + shadow_mark(past = TRUE)
animate(ani, fps = 8, 50, duration = 15,
width = 1500, height = 750, renderer = gifski_renderer())
现在,条形图通过从上一个条形向右移动来进行过渡。在此处查看当前动画:
提前感谢您的帮助!
【问题讨论】:
标签: r animation ggplot2 data-visualization gganimate