最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

RNotebook make plots in a for loop - Stack Overflow

programmeradmin4浏览0评论

i have problems with the plots in my RNotebook. Because i print them in a for-loop they appear collected at the end of the RNotebook html and not and not at the point in the code run where I would like them to be.

My data is stored in a dataframe and is transferred with this function. A new plot should appear for each entry in the dataframe.

plot_data_clean <- function(data, name){
  for (index in 1:length(data)){

        data[[index]]$hobby <- factor(
          data[[index]]$hobby,
          levels = c(
            "swimming",
            "reading",  
            "dancing"   
          )
        )

        plot <- ggplot(data[[index]]$data, aes(x = Year, y = count, fill = hobby)) +
          geom_bar(stat = "identity", position = "stack", width = 0.75) +
          ggtitle(sprintf("Hobbies over time"))+
          labs(x = "Year", y = "Amount", fill = "Legende:") + 
          theme_classic() +
          theme(
            plot.title = element_text(hjust = 0.5),  # Center title
            legend.text = element_text(size = 8),  #Smaller font for the legend
            legend.title = element_text(size = 9),  #Smaller font for the legend title
            legend.key.size = unit(0.3, "cm"),  #Smaller boxes in the legend 
            legend.position = "bottom"  #Alternatively: “bottom”, “top”, “none” (to remove) 
          ) +
          scale_x_continuous(limits = c(min(data[[index]]$data$Year)-1, max(data[[index]]$data$Year)+1), breaks = seq(min(data[[index]]$data$Year), max(data[[index]]$data$Year), 1))+
          scale_y_continuous(limits = c(0, max(data[[index]]$data$Amount), breaks = seq(0, max(data[[index]]$data$Amount, 10)) +
          scale_fill_manual(values = custom_colors)  # Sets solid colors

        
        #Save the plot as an image file
        ggsave(filename = sprintf("Hobbies %s",data[[index]]$data$Year), plot = plot, width = 10 , height = 6, dpi = 300)
      }
      #print(plot)
    }
  }
}

Calling the function

for (file in filenames_csv){

     name <- strsplit(basename(file), "ABC_")[[1]][2]
     name <- strsplit(name, "\\.")[[1]][1]

     plot_data_clean(clean_data, name)
  
}

there is another code included, but I just wanted to make it understandable.

Does anyone know a trick so that the plots are displayed one after the other in the RNotebook and not all at the end? (I would like to format this more nicely and also output the respective data tables)

(I have renamed the variables, actually my code is about something else)

发布评论

评论列表(0)

  1. 暂无评论