JSP*_*JSP 6 r bar-chart ggplot2 axis-labels gganimate
我想用这个gganim包制作一个动画条形图。条形图的坐标应通过coord_flip(即水平条)翻转,并且 x 轴应根据条的长度灵活设置通过view_follow。
考虑以下示例数据:
# Create 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))
Run Code Online (Sandbox Code Playgroud)
如果我创建一个没有 的动画条形图coord_flip,一切正常:
library("gganimate")
library("ggplot2")
# Create animated ggplot without coord_flip
ggp <- ggplot(df, aes(x = ordering, y = value)) +
geom_bar(stat = "identity", aes(fill = group)) +
transition_states(year, transition_length = 2, state_length = 0) +
view_follow(fixed_x = TRUE) # +
# coord_flip()
ggp
Run Code Online (Sandbox Code Playgroud)
但是,如果我添加coord_flip,则轴会毫无理由地左右移动:
# Create animated ggplot with coord_flip
ggp2 <- ggplot(df, aes(x = ordering, y = value)) +
geom_bar(stat = "identity", aes(fill = group)) +
transition_states(year, transition_length = 2, state_length = 0) +
view_follow(fixed_x = TRUE) +
coord_flip()
ggp2
Run Code Online (Sandbox Code Playgroud)
问题:如何翻转条形图的轴并启用灵活轴?
您可能需要考虑geom_barhggstance 包,而不是geom_bar+ coord_flip:
library(ggstance)
ggplot(df, aes(y = ordering, x = value)) +
geom_barh(stat = "identity", aes(fill = group)) +
transition_states(year, transition_length = 2, state_length = 0) +
view_follow(fixed_y = TRUE)
Run Code Online (Sandbox Code Playgroud)