rfor-loopggplot2save-image

How to generate multiple graphs with for loop in R


I would like to generate a series of graphs with for loops. For each graph I have a csv file and different titles. Each graph should be saved as PNG and SVG. Each graph is to be generated in different styles (=themes).

All the csv files have three columns (year, type, value) and the graph is a line graph with the years as X and the value for Y axis. Each "type" results in a line on the graph.

I started out creating a script for a single graph:

library(ggplot2)
library(ggthemes)

filename = "firstgraph"
filename_csv = paste0(filename,".csv")
titlestring = "Title of [firstgraph]"
labelstrings = c("\"label1\"", "\"label2\"", "\"label3\"")

my.data <- read.csv(file=filename_csv, sep = ";", header = TRUE)

# Plot
my.data %>%
  ggplot( aes(x=year, y=value, group=type, color=type)) +
  geom_line(size=1.5) +
  labs(title = titlestring, 
       subtitle = "static subtitle", 
       x = "Jahr", 
       y = "%", 
       caption = "static caption") +
  scale_x_continuous(breaks=seq(1800,2015,10)) +
  scale_y_continuous(breaks=seq(0,100,10)) +
  theme_economist() + scale_color_economist(labels = labelstrings, 
                                            name = "Variante") -> plot_1

plot_1

svg(filename=paste0("plot_",filename,".svg"), 
    width=16, 
    height=7, 
    pointsize=12)
plot_1
dev.off()

png(filename=paste0("plot_",filename,".png"), 
    type = "cairo",
    width=2000, 
    height=800, 
    pointsize=16,
    res=96)
plot_1
dev.off()

This works fine and generates a SVG and a PNG version of the said graph. Now I'd like to do this for a series of graphs and extended the script with for loops.

library(ggplot2)
library(ggthemes)

styles <- c("1", "2")
filenames <- c("firstgraph", "secondgraph")
labelstring_list <- matrix(list(), nrow=2, ncol=1)
labelstring_list[[1,1]] <- c("\"label1\"", "\"label2\"", "\"label3\"")
labelstring_list[[2,1]] <- c("\"label2_1\"", "\"label2_2\"", "\"label2_3\"")

i = as.integer(1)
for(mname in filenames) 
  {
  filename_csv = paste0(mname,".csv")
  titlestring = paste0("Entwicklung des Gebrauchs von [", mname, "]")
  labelstrings = labelstring_list[i]

  my.data <- read.csv(file=filename_csv, sep = ";", header = TRUE)

  my.data %>%
    ggplot( aes(x=year, y=value, group=type, color=type)) +
    geom_line(size=1.5) +
    labs(title = titlestring, 
         subtitle = "static subtitle", 
         x = "Jahr", 
         y = "%", 
         caption = "static subtitle") +
    scale_x_continuous(breaks=seq(1800,2015,10)) +
    scale_y_continuous(breaks=seq(0,100,10)) -> plot_1

  for(style in styles)
    {
    if(style=="1") 
      {
      plot_1 +
        theme_economist() + scale_color_economist(labels = labelstrings, 
                                                  name = "Variante") -> plot_x
      }
    if(style=="2") 
      {
      plot_1 +
        theme_wsj()+ scale_colour_wsj("colors6",labels = labelstrings, 
                                      name = "Variante") -> plot_x
      }

    svg(filename=paste0("plot_",mname,"_",style,".svg"), 
        width=16, 
        height=7, 
        pointsize=12)
      plot_x
    dev.off()

    png(filename=paste0("plot_",mname,"_",style,".png"), 
        type = "cairo",
        width=2000, 
        height=800, 
        pointsize=16,
        res=96)
      plot_x
    dev.off()

    }

  i = (i+1)
  }

This does not work anymore. I have no errors in the console and the following files are created:

These files are all 223 bytes and are empty. The expected PNG files are NOT created.

I checked with print() if the right names and such are in the variables and all seems fine:

  print(mname)
  print(filename_csv)
  print(titlestring)
  print(labelstrings)

This outputs:

[1] "firstgraph"
[1] "firstgraph.csv"
[1] "Entwicklung des Gebrauchs von [firstgraph]"
[[1]]
[1] "\"label1\""   "\"label2\"" "\"label3\"" 

[1] "secondgraph"
[1] "secondgraph.csv"
[1] "Entwicklung des Gebrauchs von [secondgraph]"
[[1]]
[1] "\"label2_1\""   "\"label2_2\"" "\"label2_3\"" 

This seems all fine to me but as I said, the PNGs are not created and the SVGs are empty. I tried generating only PNGs (and no SVGs) which did not work.

Could anyone tell me where I make a mistake?

Thanks a lot.


Solution

  • Can you try to replace

    png(filename=paste0("plot_",mname,"_",style,".png"), 
        type = "cairo",
        width=2000, 
        height=800, 
        pointsize=16,
        res=96)
      plot_x
    dev.off()
    

    by

    plot_x
    mirror <- recordPlot()
    png(filename=paste0("plot_",mname,"_",style,".png"), 
        type = "cairo",
        width=2000, 
        height=800, 
        pointsize=16,
        res=96)
    replayPlot(mirror)
    dev.off()
    

    in your loop and re-test ?