R saving blank empty plots when executed in a loop

I am trying to run the following code, which makes use of the library "kaos" which has its own cgr.plot() function. The goal is to generate an image for each 'seq' in the dataframe. I can obtain the plots for particular cases (for example, i=5), however when I run the for loop, it ends up saving empty images.

What is happening? Are there background processes that need to be terminated in each loop?
I have tried with dev.copy(png, save_path) before dev.off() but it still doesn't work.

I am new to R, all help is welcome.


file_path <- "saved_experiment_Rdata.csv"

# Read the CSV file
df <- read.csv(file_path)

folder_path <- "xxx/images"    # i have here the actual address

# Iterate through rows
for (i in 1:nrow(df)) {
  # Access values in each row
  name <- df[i,'IsolateName']
  seq <- strsplit(df[i,'seq'],"")[[1]]

  file_name <- paste0(name,'.jpg')
  save_path <- file.path(folder_path, file_name)
  ### encoding the sequence
  seq.cgr = cgr(seq, res = 100)
  # Save the plot to a PNG file

  cgr.plot(seq.cgr, mode = "matrix")


It seems cgr.plot() actually uses {ggplot2} under the hood, not base R plots. You can see that in its source code.

So you can easily save the result using ggsave(), for example:


  plot <- cgr.plot(seq.cgr, mode = "matrix")
  ggplot2::ggsave(save_path, plot)

If you look at the options of ggssave(), you will see that you have actually a lot more control, for example you can use

ggplot2::ggsave(filename = file_name, plot, path = folder_path)

This topic was automatically closed 42 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.