【问题标题】:How do I make geom_bar colors change with gganimate when x and y are constant?当 x 和 y 不变时,如何使 geom_bar 颜色随 gganimate 变化?
【发布时间】:2021-08-29 10:28:59
【问题描述】:

我是 gganimate 的新手,很难弄清楚如何操作。

我想通过动画颜色过渡来显示变量在两个不同级别的分布。我想通过让narrow level 在相同时间内通过比wider level 更小的颜色范围来展示这一点。这可能吗?

这是我到目前为止的可重现示例。

library(ggplot2)
df <- data.frame(x = rep(c("narrow", "wide"), each = 1000),
                 y = c(sort(runif(n = 1000, min = 6, max = 7)),
                       sort(runif(n = 1000, min = 3, 10))),
                 animate.time = c(1:1000))

ggplot(data = df, aes(x = x, fill = y)) + 
  geom_bar() 

由reprex package (v2.0.0) 于 2021 年 6 月 12 日创建

作为其中的一部分,每个条使用的色标应该相同,但narrow x 应该比wide x 占据更窄的颜色范围。

我使用了geom_bar,因为我不希望可视化的形状发生变化,但是我不确定如何进行。我尝试添加animate.time,以便gganimate 可以逐步完成,但是我不明白我应该如何让它根据y 改变颜色。

如果有任何指点,我将不胜感激。

【问题讨论】:

    标签: r ggplot2 gganimate


    【解决方案1】:

    基于this 有一种更简单的方法。

    library(colorspace)
    library(gganimate)
    library(ggplot2)
    
    # Narrow Visualization
    
    narrow<-data.frame(x = rep(10,10),
                          state_cont=rep(1:2, each = 5))
    
    ggplot(data = narrow, aes(x = x, fill = state_cont)) +
      geom_bar() +
      colorspace::scale_fill_continuous_sequential(palette = "Reds 3", begin = 0.4, end = .6) +
      transition_states(states = state_cont) + theme_void() + 
      theme(legend.position = "none")
    

    # Wide Visualization
    wide <- data.frame(x=rep(10,10),
                           state_cont=rep(1:2, each = 5))
    
    ggplot(data = wide, aes(x = x, fill = state_cont)) +
      geom_bar() +
      colorspace::scale_fill_continuous_sequential(palette = "Reds 3", begin = 0, end = 1) + 
    transition_states(states = state_cont) + theme_void() + theme(legend.position = "none")
    

    解释是,对于这个特定问题,您不想设置它应该振荡的每一个值,通过begin 和end 参数。然后gganimate会根据state_cont自动循环遍历

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多