Graph Not Changing Colors

I wrote the following procedure in R:

  • Start with a data frame called "girafe" data
  • Sample 30% of this data and label it "sample"
  • Create a histogram for this data, and color the areas of this histogram that were "sampled" as one color, and the other rows another color
  • Repeat this process 100 times and make an animation of this process

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)

enter image description here

But for some reason, this graph does not change colors in the animation.

Can someone please show me how to fix this?

Note : I was able to get the colors to change with the following code:

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)

enter image description here

But this shows the two colors as two separate "groups". I want there to be only one "group", but there to be different colors within this one "group". Can someone please show me how to fix this?

Thanks

Here's one idea I had.



animate(
  ggplot() + aes(x=a, fill = col) + 
    geom_histogram(data=filter(results_df,sample=="sample"),
                   binwidth=1) +  
    geom_histogram(data=filter(results_df,sample!="sample"),
                   binwidth=1) + 
    scale_fill_manual( values = c('blue', 'red')) +
   facet_wrap(    ~sample    )+
    transition_states(iteration, state_length = 0.2) +
    labs(title = "Group: {closest_state}"),
  fps = 25)

idea

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.