【问题标题】:Graph Not Changing Colors in RR中的图形不改变颜色
【发布时间】:2021-11-28 20:52:33
【问题描述】:

我在 R 中编写了以下程序:

  • 从名为“giraffe”数据的数据框开始

  • 抽取 30% 的数据并将其标记为“样本”

  • 为此数据创建一个直方图,并将该直方图“采样”的区域着色为一种颜色,其他行另一种颜色

  • 重复这个过程100次,制作这个过程的动画

    library(ggplot2)
      library(dplyr)
      library(gganimate)
    
      giraffe_data <- data.frame( a = abs(rnorm(1000,17,10)), b = abs(rnorm(1000,17,10)))
    
      results <- list()
    
    
    
      for( i in 1:100) 
    
      {
    
          giraffe_data_i <- giraffe_data 
          a_i <- c("sample", "not_sampled")
          aa_i <- as.factor(sample(a_i, 1000, replace=TRUE, prob=c(0.3, 0.7)))
          giraffe_data_i $col = cut(giraffe_data_i$a, c(-Inf, 17, Inf))
          giraffe_data_i$sample <- aa_i
          giraffe_data_i$iteration <- i + 1
    
    
    
          results[[i]] <- giraffe_data_i
    
      }
    
      results
      results_df <- do.call(rbind.data.frame, results)
    
    
    
    
      animate(
        ggplot(results_df, aes(x=a, fill = col)) + 
        geom_histogram(binwidth=1) +  
        scale_fill_manual(breaks = levels(results_df$col), values = c('blue', 'red')) +
        transition_states(iteration, state_length = 0.2) +
        labs(title = "Group: {closest_state}"),
        fps = 25)
    

但由于某种原因,这个图表在动画中没有改变颜色。

谁能告诉我如何解决这个问题?

谢谢

注意:我可以使用以下代码更改颜色:

animate(
    ggplot(results_df, aes(x=a, color = sample)) + 
        geom_histogram(fill="white", position="dodge")+  
        transition_states(iteration, state_length = 0.2) +
        labs(title = "Group: {closest_state}"),
    fps = 5)

但这将两种颜色显示为两个单独的“组”。我希望只有一个“组”,但在这个“组”中有不同的颜色。有人可以告诉我如何解决这个问题吗?

谢谢

【问题讨论】:

    标签: r ggplot2 data-manipulation gganimate


    【解决方案1】:

    有时我发现对 gganimate 上游的数据进行转换更容易。因此,这是一种对数据进行分箱并为每次迭代计数,然后绘制为普通列几何图形的方法。

    library(tidyverse); library(gganimate)
    # bins of width 2
    bin_wid = 2
    results_df_bins <- results_df %>%
      # "col" is set at 17 but my bins are at even #s, so to align 
      #   bins with that I offset by 1
      mutate(a_bin = floor((a + 1)/ bin_wid)*bin_wid) %>%
      count(a_bin, col, sample, iteration) %>%
      mutate(sample = fct_rev(sample)) # put "sample" first
    
    animate(
      ggplot(results_df_bins, aes(x=a_bin, y = n, fill = sample)) + 
        geom_col(position = position_stack(reverse = TRUE)) +
        transition_states(iteration, state_length = 0.2) +
        labs(title = "Group: {closest_state}"),
      fps = 25, nframes = 500, height = 300)
    

    【讨论】:

    • 感谢您的回答!我想知道为什么蓝条也没有改变颜色?我还在努力!非常感谢您的帮助!
    • 我在这里发布了一个相关问题:stackoverflow.com/questions/69509234/…
    • (另外,你如何在stackoverflow的答案中插入动画?非常酷!)
    • 当我运行animate() 行时,会在 RStudio 的查看器窗口中创建一个 GIF,我右键单击以保存,然后像添加 PNG 一样添加到 SO,使用添加图片图标。
    猜你喜欢
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2023-01-26
    相关资源
    最近更新 更多