【问题标题】:gganimate with multiple points for same x valuegganimate 具有相同 x 值的多个点
【发布时间】:2021-10-19 14:50:52
【问题描述】:

我有一些数据,其中单个 x 坐标值的多个 y 坐标值。它类似于此问题中包含的问题。它还有一个state 变量,必须用于gganimate 中的transition_state() 函数。

library(data.table)

df <- data.table(
  x = seq(11),
  type1 = c(2, 3, 2.5, 3, 2, 2, 3, 2.5, 3.5, 3, 2),
  type2 = c(NA, 3, 3.5, 3, NA, NA, 3, 3.5, 4, 3, NA)
)
m.df <- melt.data.table(df, "x", variable.name = "grp")
m.df[x %in% seq(5), "state" := 1][x %in% seq(6, 11), "state" := 2]
m.df
#>      x   grp value state
#>  1:  1 type1   2.0     1
#>  2:  2 type1   3.0     1
#>  3:  3 type1   2.5     1
#>  4:  4 type1   3.0     1
#>  5:  5 type1   2.0     1
#>  6:  6 type1   2.0     2
#>  7:  7 type1   3.0     2
#>  8:  8 type1   2.5     2
#>  9:  9 type1   3.5     2
#> 10: 10 type1   3.0     2
#> 11: 11 type1   2.0     2
#> 12:  1 type2    NA     1
#> 13:  2 type2   3.0     1
#> 14:  3 type2   3.5     1
#> 15:  4 type2   3.0     1
#> 16:  5 type2    NA     1
#> 17:  6 type2    NA     2
#> 18:  7 type2   3.0     2
#> 19:  8 type2   3.5     2
#> 20:  9 type2   4.0     2
#> 21: 10 type2   3.0     2
#> 22: 11 type2    NA     2
#>      x   grp value state

使用 gganimate 绘制数据,如下所示。

library(ggplot2)

ggplot(m.df, aes(x, value, group = grp, color = grp)) +
  geom_line(na.rm = T) +
  geom_point(na.rm = T) +
  theme_bw()

剧情可以找到HERE

我想使用gganimatetransition_state()函数使用数据中的状态列如下图,但是显示错误。

library(gganimate)

ggplot(m.df, aes(x, value, group = grp, color = grp)) +
  geom_line(na.rm = T) +
  geom_point(na.rm = T) +
  transition_states(state)
#> Error in rep(seq_len(nrow(polygon)), splits + 1): invalid 'times' argument

我在这里做错了什么?

提前谢谢你

【问题讨论】:

    标签: r ggplot2 gganimate


    【解决方案1】:

    使您的代码工作的一个选项是使用例如grpstate 进行分组。 interaction。否则gganimate 无法通过state 拆分您的数据,因为每个组中都存在这两种状态。此外,您必须将group aes 放在color aes 之后。否则你会遇到同样的问题:

    library(ggplot2)
    library(gganimate)
    
    ggplot(m.df, aes(x, value, color = grp, group = interaction(grp, state))) +
      geom_line(na.rm = T) +
      geom_point(na.rm = T) +
      transition_states(state)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2020-12-15
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多