Home > database >  Is there a way to save multiple ggplots to a single PDF while using a for loop?
Is there a way to save multiple ggplots to a single PDF while using a for loop?

Time:12-08

My current code:

library(pdftools)
plot <- NA

Indicator <-  unique(map_and_data$Indicator) 
plot<-list (1:length(Indicator))

for (i in 1 : length(Indicator))  
{
  df = map_and_data[map_and_data$Indicator==Indicator[[i]],]
  plot[[i]]<- ggplot() 
          geom_sf(aes(fill=df$NFHS5),color="black",data=df$geometry) 
          labs(title = Indicator[[i]]) 
   ggsave("test.pdf", plot[[i]], device = "pdf")
  

}

What I want is to save all the plots(maps) in the same file. The issue is that it runs the loop and saves for the last Indicator(in this case it's 104) only. How should I go about solving this problem?

CodePudding user response:

Make sure px is a ggplot object, and you can try:

plot <- list(p1, p2, p3, p4)
pdf('plot.pdf', width=5, height=5)
plot
dev.off()

This code is worked on the jupyter notebook environment. You can also modify the list plot by for loop if you want.

CodePudding user response:

Here is how I would do this. Below I'm using a standard dataset and plot to enable quickly testing the code. Of course in the real case you should use your own data and plotting code.

library(ggplot2)

# In real case this would point to some file
temp <- tempfile(fileext = ".pdf")
# Open the PDF device
pdf(temp)

# Do the looping
for (i in 1:3) {
  p <- ggplot(mpg, aes(displ, hwy))  
    geom_point()  
    ggtitle(i)
  # Make sure to print the result
  print(p)
}

# Close the PDF device
dev.off()

# Optionally:
file.show(temp)

Alternatively, you could use a list to store plots and print them to PDF as follows:

library(ggplot2)

# Create list of plots
plot_list <- list()
for (i in 1:3) {
  plot_list[[i]] <- ggplot(mpg, aes(displ, hwy))  
    geom_point()  
    ggtitle(i)
}

# Open the PDF device at some file
temp <- tempfile(fileext = ".pdf")
pdf(temp)

# Print the list of plots
lapply(plot_list, print)

# Close the PDF device
dev.off()

CodePudding user response:

You could just put the plots in an RMarkdown File and render it as a pdf.

So the code block that you're going to have will look like this:

   ```{r echo=FALSE, message=FALSE, warning=FALSE}

    library(tidyverse)
    
    Indicator <-  unique(map_and_data$Indicator) 
    
    for (i in 1 : length(Indicator))  
    {
      df = map_and_data[map_and_data$Indicator==Indicator[[i]],]
          ggplot() 
              geom_sf(aes(fill=df$NFHS5),color="black",data=df$geometry) 
              labs(title = Indicator[[i]]) 
    
    }

    ```

CodePudding user response:

You can try first creating the pdf, then printing each plot from your list of plots, and then closing the pdf.

This would look like this:

pdf("test.pdf")  # open the pdf file 
plots[1:length(Indicator]  # print each plot from the list into the file 
dev.off()  # close the file 

CodePudding user response:

I don't have your data so I can't test the code, but maybe you can try something like this:

---
title: "R Notebook"
output:
pdf_document: default
html_notebook: default
---

```{r}
library(tidyverse)

Indicator <- unique(map_and_data$Indicator) 
plot <- list(1:length(Indicator))

for (i in 1 : length(Indicator))  
{
  df = map_and_data[map_and_data$Indicator==Indicator[[i]],]
  plot[[i]]<- ggplot() 
          geom_sf(aes(fill=df$NFHS5),color="black",data=df$geometry) 
          labs(title = Indicator[[i]])
  plot[[i]]
}
```

Like in the answer mentioned above, you can use something like RStudio to "knit to pdf" which will create a pdf file with your plots.

CodePudding user response:

You haven't given me data to check, but you need to "start" a pdf file outside the loop.

pdf(test.pdf)
for (i in 1 : length(Indicator))  
{
  df = map_and_data[map_and_data$Indicator==Indicator[[i]],]
  plot[[i]]<- ggplot() 
          geom_sf(aes(fill=df$NFHS5),color="black",data=df$geometry) 
          labs(title = Indicator[[i]])
}
dev.off()

Everytime plot is called it is getting put inside the pdf, then when dev.off() runs it closes off the pdf file saving it.

  • Related