Plot over multiple pages using ggplot in R
Hello friends! Today we’ll be learning how to create plots over multiple pages and export as pdf using ggplot in R. Easy to follow code with sample file attached in the tutorial.
Import Packages
library(ggplot2) library(dplyr) library(ggforce) library(qpdf)
Import Data and manipulation
df <- read.csv("df.csv") #getting count of rows and changing to df df1 <- df %>% group_by(AREA.NAME,month,year) %>% summarise( CrimeCount = n()) df2 <- as.data.frame(df1) #factoring month column for plotting df2$month <- as.factor(df2$month) #recode month to monthName df2 <- df2 %>% mutate(MonthName = recode(month, "1" = "Jan", "2" = "Feb", "3" = "Mar", "4" = "Apr", "5" = "May", "6" = "Jun", "7" = "Jul", "8" = "Aug", "9" = "Sep", "10" = "Oct", "11" = "Nov", "12" = "Dec" ))
Plot
#plot p <- ggplot(df2) + geom_point(aes(MonthName, CrimeCount)) + facet_wrap_paginate(~ year+AREA.NAME, ncol = 5, nrow = 2)
Exporting to individual pdf files
#removing if there is any file file.remove("mergefinal.pdf") #exporting to individual pdf files for(i in 1:n_pages(p)){ p_save <- p + facet_wrap_paginate(~ year+AREA.NAME, ncol = 5, nrow = 2, page = i) ggsave(plot = p_save, height = 7 , width = 7 * 2.5, filename = paste0('exportChart_', i, '.pdf')) } #combining pdf pdf_combine(input = list.files(full.names=TRUE,pattern=".pdf"), output = "mergefinal.pdf") #removing the individual plots for(i in 1:n_pages(p)){ file.remove(paste0("exportChart_",i, '.pdf')) }
Check the working code with file here
Keep visiting Analytics Tuts for more tutorials.
Thanks for reading! Comment your suggestions and queries