通过gganimate制作的动画条形图:view_follow和coord_flip冲突

时间:2019-02-12 09:24:27

标签: r ggplot2 bar-chart 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))

如果我创建没有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

enter image description here

但是,如果我添加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

enter image description here

问题:如何翻转条形图的轴并启用柔性轴?

1 个答案:

答案 0 :(得分:1)

您可能要考虑使用ggstance软件包中的geom_barh,而不是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)

animated plot