Search code examples
rfor-loopggplot2

For loop ggplot not working- plotting same plot


I am trying to use the followig code to plot several columns of frequency data into histograms.

colsToPlot <- c(61,63,65,67,69,71,73,75)
for (i in 1:length(colsToPlot)){
  Outcome = ResearcherData[,(colsToPlot[i])]
  out[[i]] <- ResearcherData %>%
    filter(is.na(Outcome) == FALSE,
           Outcome!= "")%>%
    ggplot(aes(x= Outcome)) + geom_bar(stat = "count", fill = "#1E4D2B" ) + 
    scale_x_discrete(drop=FALSE) + 
    theme_bw() + theme(
      axis.title.x = element_blank(), axis.ticks.x = element_blank(),
      axis.title.y = element_blank(),
      legend.position= "none"
      
    )+ ggtitle(colnames(ResearcherData[,i]))+
    theme(plot.title = element_text(hjust = 0.5))
    
}
    

grid.arrange(out[[1]],out[[2]],out[[3]],out[[4]],out[[5]],out[[6]],out[[7]],out[[8]], ncol=2)

However, it is just giving me 8 of the same histogram. Any ideas what might be wrong?


Solution

  • Using lapply:

    plot_data <- function(data, col) {
      dplyr::select(data, all_of(col)) |>
        ggplot(aes_string(x = col)) + 
        geom_histogram(binwidth = 10, fill = "#1E4D2B", color = "white") + 
        theme_bw() + 
        theme(axis.title.x = element_blank(), 
              axis.ticks.x = element_blank(),
              axis.title.y = element_blank(),
              legend.position = "none") + 
        ggtitle(col) +
        theme(plot.title = element_text(hjust = 0.5))
    }
    
    cowplot::plot_grid(
        plotlist=lapply(colnames(ResearcherData)[colsToPlot], 
                        FUN=plot_data, data=ResearcherData), 
                      ncol=2)
    

    set.seed(1)
    ResearcherData <- data.frame(matrix(sample(1:100, 1500, replace = TRUE), 
                                        nrow = 100, ncol = 15))
    
    # Columns to plot
    colsToPlot <- c(1, 3, 5, 7, 9, 11, 13, 15)