【问题标题】:Transitioning between two different geom_smooth() objects in gganimategganimate 中两个不同的 geom_smooth() 对象之间的转换
【发布时间】:2020-10-31 07:15:03
【问题描述】:

我在使用 gganimate 时遇到了困难,我将不胜感激。

我对两个连续变量之间的关系在因子变量的两个值之间有何不同感兴趣。想象一下,比如说,我对在给定干预前后考试成绩和身高之间的关系如何变化感兴趣。我的数据大致有以下结构:

set.seed(24601)

height <- rnorm(10, 0, 1)

test_data <- 
  tibble(height = rep(height, 2),
         test_scores = rnorm(20, 0, 1),
         before_or_after = c(rep("before", 10), rep("after", 10)),
         id = rep(c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), 2))

如果我想在静态 ggplot 中显示它,我可以这样做:

ggplot(data = test_data) +
  aes(x = height,
      y = test_scores,
      colour = before_or_after) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

但我有兴趣关注干预前后测试分数的变化,因此希望为每个观察和 geom_smooth() 设置动画。

我可以按如下方式为每个观察设置动画:

ggplot(data = test_data) +
  aes(x = height,
      y = test_scores,
      group = id) +
  geom_point() +
  transition_states(before_or_after)

但理想情况下,我会执行以下操作:

ggplot(data = test_data) +
  aes(x = height,
      y = test_scores,
      group = id) +
  geom_point() +
  geom_smooth(method = "lm", 
              se = FALSE) +
  transition_states(before_or_after)

geom_smooth 沿着点移动。但是,当我这样做时,我会收到错误消息

Error in `$<-.data.frame`(`*tmp*`, "group", value = "") : 
  replacement has 1 row, data has 0

如果有人能告诉我如何解决这个问题,我将不胜感激!

【问题讨论】:

    标签: r ggplot2 gganimate


    【解决方案1】:

    在您的程序中使用transition_manual(before_or_after) 而不是transition_states(before_or_after)。然后你得到以下输出:

    【讨论】:

    • 你知道是否有可能让点和 geom_smooths 在状态之间移动,而不仅仅是这里显示的两个静止图像?类似于上面的例子,transition_states(before_or_after) 中的点上下移动,但 geom_smooths 也上下移动。
    • 我不确定geom_smooth 是这些状态结束时点的静态表示。
    猜你喜欢
    • 2012-09-10
    • 2017-11-13
    • 2020-01-26
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多