简体   繁体   中英

Iterating with ggsave and ggplot2

I have a folder containing csv files. I am iterating over these csv files and creating one plot per csv file. I can do this via:

setwd("/myfiles/folder")
filenames = dir(pattern="*.csv")
for (i in 1:length(filenames)) { 
  tmp <-read.csv(filenames[i]); 
  print(ggplot(aes(x = count, y = time), data = tmp) + geom_point(aes(color = id)) 
      + geom_smooth(aes(color = id), method= "lm", se = F, formula=y ~ poly(x, 3, raw=TRUE)) 
      + ggtitle("Title") + labs(x="Count)",y="Time")+ggsave(file="ID_.jpeg"))
}

However, as you would expect this only creates one .jpeg file and thus it is overwritten each time and I am left with the final plot saved.

I have tried:

for (i in 1:length(filenames)) { 
  tmp <-read.csv(filenames[i]); 
  print(ggplot(aes(x = count, y = time), data = tmp) + geom_point(aes(color = id)) 
       + geom_smooth(aes(color = id), method= "lm", se = F, formula=y ~ poly(x, 3, raw=TRUE)) 
       + ggtitle("Title") + labs(x="Count)",y="Time")+ggsave(file="ID"+id+".jpeg"))
}

But this results in:

Error in regexpr("\\.([[:alnum:]]+)$", x) : object 'id' not found

Why is the id not recognised by ggsave when it is previously (for the geom_plot item)?

Try this,

for (ii in seq_along(filenames)) { 

  tmp <- read.csv(filenames[ii])

  p <- ggplot(aes(x = count, y = time), data = tmp) + 
          geom_point(aes(color = id)) + 
          geom_smooth(aes(color = id), method= "lm", se = F, 
                     formula=y ~ poly(x, 3, raw=TRUE)) + 
          ggtitle("Title") + 
          labs(x="Count)",y="Time")

  ggsave(file=paste0("ID", ii, ".png"), p)
}

Because in ggplot you provide data (in your case it is tmp) which has a column ID). While in ggsave it doesn't ask for data, so when you give a column name ID, ggsave doesn't know what to do with it.

What I suggest is to use i (your for iterator) in ggsave.

for (i in 1:length(filenames)) { 
tmp <-read.csv(filenames[i]); 
print(ggplot(aes(x = count, y = time), data = tmp) +   geom_point(aes(color = id)) 
   + geom_smooth(aes(color = id), method= "lm", se = F, formula=y ~ p  oly(x, 3, raw=TRUE)) 
   + ggtitle("Title") + labs(x="Count)",y="Time")+ggsave(file=paste0("ID",i,".jpeg"))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM