Search code examples
rfor-loopplotwaffle-chart

How to make multiple plots with a for loop?


I was experimenting with the waffle package in r, and was trying to use a for loop to make multiple plots at once but was not able to get my code to work. I have a dataset with values for each year of renewables,and since it is over 40 years of data, was looking for a simple way to plot these with a for loop rather than manyally year by year. What am I doing wrong? I have it from 1:16 as an experiment to see if it would work, although in reality I would do it for all the years in my dataset.

for(i in 1:16){
renperc<-islren$Value[i]
parts <- c(`Renewable`=(renperc), `Non-Renewable`=100-renperc)
waffle(parts, rows=10, size=1, colors=c("#00CC00", "#A9A9A9"), 
       title="Iceland Primary Energy Supply", 
       xlab=islren$TIME)
}


Solution

  • UPDATE: The code simply wasn't plotting anything when i tried putting in anything above one value (ex. 1:16) or a letter, both in terms of separate plots or many in one plot window (which I think perhaps waffle does not support in the same way as regular plots). In the end, I managed by making it into a function, although I'm still not sure why my original method wouldn't work if this did. See the code that worked below. I also tweaked it a bit, adding ggsave for example.

        #function
        waffling <- function(x){
        renperc<-islren$Value[x]
        parts <- c(`Renewable`=(renperc), `Non-Renewable`=100-renperc)
        waffle(parts, rows=10, size=1, colors=c("#00CC00", "#A9A9A9"), title="", 
        xlab=islren$TIME[x])
        ggsave(file=paste0("plot_", x,".png"))}
    
        for(i in 1:57){
        waffling(i)
        }