通过gganimate制作的动画条形图:view_follow&的冲突coord_flip [英] Animated barplot via gganimate: conflict of view_follow & coord_flip

查看:85
本文介绍了通过gganimate制作的动画条形图:view_follow&的冲突coord_flip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用gganim包创建动画的条形图.条形图的坐标应通过coord_flip(即水平条)翻转,并且x轴应根据view_follow的条长而灵活.

I want to crate an animated barchart with the gganim package. The coordinates of the barchart should be flipped via coord_flip (i.e. horizontal bars) and the x-axis should be made flexible depending on the length of the bars via 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的动画条形图,则一切正常:

If I create an animated barchart without coord_flip, everything works fine:

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

但是,如果我添加coord_flip,则轴无缘无故地从一侧移到另一侧:

However, if I add coord_flip, the axes are moving from side to side without any reason:

# 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

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

推荐答案

您可能要考虑使用ggstance软件包中的geom_barh,而不是geom_bar + coord_flip:

You may want to consider geom_barh from the ggstance package, instead of 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)

这篇关于通过gganimate制作的动画条形图:view_follow&amp;的冲突coord_flip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆