我正在尝试在四个堆叠条形图之间进行转换。输出并不完全符合我的预期,我无法确定这是否是我的代码中的错误,或者是否是我的代码中的错误gganimate
R 包。
这是我使用的数据框:
df <- structure(list(name = c("variable", "variable", "variable", "variable",
"variable", "variable", "variable", "variable", "variable", "variable",
"variable", "variable", "variable"), groups = structure(c(3L,
3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 4L, 4L, 4L), .Label = c("group 1",
"group 2", "group 3", "group 4"), class = "factor"), score = structure(c(4L,
3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L), .Label = c("4",
"3", "2", "1"), class = c("ordered", "factor")), percentage = c(8,
38, 38, 16, 17.1428571428571, 40, 42.8571428571429, 40, 20, 40,
5, 65, 30), percentage2 = c("8%", "38%", "38%", "16%", "17.1%",
"40%", "42.9%", "40%", "20%", "40%", "5%", "65%", "30%"), label = c(0.04,
0.27, 0.65, 0.92, 0.0857142857142857, 0.371428571428571, 0.785714285714286,
0.2, 0.5, 0.8, 0.025, 0.375, 0.85)), row.names = c(NA, -13L), class = "data.frame")
当我制作仅包含一个阶段的组变量的堆积条形图时,我得到例如这:
library(ggplot2)
library(dplyr)
ggplot(filter(df, groups == "group 3"),
aes(x = name, y = percentage, fill = score)) +
geom_bar(stat = "identity", position = "fill", width = 0.8) +
geom_text(aes(y = label, label = percentage2), color = "grey25") +
coord_flip() +
scale_fill_manual(values=c("darkgreen", "lightgreen", "yellow", "red"),
guide = guide_legend(reverse = TRUE), drop=FALSE)
但是当我尝试添加gganimate
四个不同小组阶段的动画我得到的是:
library(gganimate)
ggplot(df, aes(x = name, y = percentage, fill = score)) +
geom_bar(stat = "identity", position = "fill", width = 0.8) +
geom_text(aes(y = label, label = percentage2), color = "grey25") +
coord_flip() +
scale_fill_manual(values = c("darkgreen", "lightgreen", "yellow", "red"),
guide= guide_legend(reverse = TRUE), drop = FALSE) +
transition_states(groups, transition_length = 2, state_length = 1)
它似乎同时将所有组的所有百分比(条长度)添加到动画中。我想要四个不同组的堆叠条形图之间没有间隙的过渡。我怎样才能让这个动画在条形之间进行无间隙的过渡?