【问题标题】:How to un-alphabetize frame order in gganimate?如何在 gganimate 中取消字母顺序的帧顺序?
【发布时间】:2020-03-11 20:26:00
【问题描述】:

我有一个数据框,每个月都有观察结果。我想每个月创建一个观察结果的 gif 图像。然而,在 gganimate 中,帧是按字母顺序排列的(例如,从四月开始而不是一月)。如何更改帧的顺序?

或者,我可以使用月份数来使绘图正确运行。但是,在这种情况下,我必须将框架标题更改为一月、二月、三月等,而不是 1、2、3 ...我意识到 this response 可以解决问题,但它仍然不能回答是否或者是否有可能以某种方式指定 gganimate 中的帧顺序。

monthly.data <- data.frame(month = rep(c("January", "February", "March", "April", "May","June", "July", "August", "September", "October", "November", "December"), 10), xval = rnorm(n = 120,10,3), yval=rnorm(120,10,3))

    # This plots it in alphabetical order
    ggplot(monthly.data, aes(x = xval, y = yval))+
      geom_point()+
      transition_states(month)+
      ggtitle("{closest_state}")

    # Ordering the dataframe correctly doesn't help
    mothly.data <- arrange(monthly.data, factor(month, levels = c("January", "February", "March", "April", "May","June", "July", "August", "September", "October", "November", "December")))

    ggplot(monthly.data, aes(x = xval, y = yval))+
      geom_point()+
      transition_states(month)+
      ggtitle("{closest_state}")

【问题讨论】:

  • monthly.data$month = factor(monthly.data$month, levels = month.name),使用内置的 month.name 向量,该向量具有正确的月份顺序。行的顺序无关紧要。因子水平的顺序很重要。

标签: r ggplot2 gganimate


【解决方案1】:

ggplot 在绘图时关心因子水平的顺序。

您可以从一开始就将月份向量创建为具有所需级别的factor,这取决于您。

编辑:参考@Gregor Thomas 的评论

monthly.data$month = factor(monthly.data$month, levels = month.name)

【讨论】:

  • relevel 似乎是一种糟糕的做法......为什么一次一个级别?
  • 是的,最好在开头定义为factor。当然,还有其他库可以批量重新调整,但据我所知,重新调整一次只接受一个参数。
  • 没错,就是你这样做的方式,哈哈。 monthly.data$month = factor(monthly.data$month, levels = month.name)
  • 对,relevel 用于将关卡设为第一关。如果要更改所有级别,只需再次使用factor。仅仅因为您第一次没有一次性指定所有级别并不意味着您现在不能这样做。
  • @eonurk 谢谢!这非常有效。我以为我将它更改为排列()命令中的一个因子,但我现在看到我只是按因子列表排序了一个字符向量。菜鸟失误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多