Looping over plots

2019-08-03 03:58发布

I try to generate a lot of plots and save them in separate files. Each plot should be based on a variable from a dataframe.

This works when using the numbers of the variables:

for(i in names(df)[19:20]) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +   
   theme_bw())
   dev.off()
}

However, it doesn't work if I'm using variable names instead of the ordered number. I don't understand why.

for(i in names(df)[c("varname1","varname2","varname3")]) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +            
   theme_bw())
   dev.off()
}

I get the following error message at the latter question (if it's exactly the same variable as in the first example):

"Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"? "

Any ideas?

标签: r loops ggplot2
1条回答
Fickle 薄情
2楼-- · 2019-08-03 04:15

names(df) is an unnamed vector, so it doesn't make sense to select named values from that vector.

What you're looking for is

for(i in c("varname1","varname2","varname3")) {
   png(paste(i, "png", sep = "."), width = 400, height = 400)
   print(ggplot(df) + geom_histogram(aes_string(x= i), binwidth= 0.4) +            
   theme_bw())
   dev.off()
}
查看更多
登录 后发表回答