Major
Major

Reputation: 199

R: Cannot Output Plots To Files From A Loop

I am trying to output a series of the file using the R.

Usually, we can use the following code to output a plot:

jpeg("XXXXX_XXXX.jpg")

ggplot(data=YEAR_ZIP_DATA, aes(x=SOME_VARIABLE)) + geom_bar()

dev.off()

The above code can get me a file in the current working directory called XXXXX_XXXX.jpg

Now I want to write a loop to create a series of file: for each year, draw a bar chart for each zip code and save to the current directory. Here is the code:

# year_list: a list of distinctive years
for(year in year_list){
  # zip_list: a list of distinctive zip codes
  for(zip in zip_list){
    # some code to get a filename like 10010_2018.jpg
    filename <- (some code)

    # some code to subset the data to get the current zip and year
    year_zip_data <- (some code)

    jpeg(filename)

    ggplot(data=year_zip_data, aes(x=SOME_VARIABLE)) + geom_bar()

    dev.off()
  }
}

However, after the above loop, there is nothing in the current working directory... How should I solve the problem?

Thanks in advance!

Upvotes: 0

Views: 139

Answers (1)

Jakub Kuž&#237;lek
Jakub Kuž&#237;lek

Reputation: 36

Try ggsave function. It directly saves the graphics object created by ggplot.

Upvotes: 1

Related Questions