简体   繁体   中英

ggplot - plotting charts on multiple pages

My dataset looks like this:

df = structure(list(sl = 1:20, iso3 = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L
), .Label = c("ATG", "EGY"), class = "factor"), year = c(2000L, 
2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 
2010L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L, 2018L, 
2000L), Var1 = c(NA, NA, NA, NA, NA, NA, NA, 144L, 45L, NA, NA, 
NA, NA, NA, NA, NA, NA, 282L, NA, NA), Var1_imp = c(144, 144, 
144, 144, 144, 144, 144, 144, 45, 71.3, 97.7, 124, 150, 177, 
203, 229, 256, 282, 282, 38485), Var2 = c(NA, NA, NA, NA, NA, 
NA, NA, 277L, NA, NA, NA, NA, NA, 421L, 434L, 422L, 424L, 429L, 
435L, NA), Var2_imp = c(277L, 277L, 277L, 277L, 277L, 277L, 277L, 
277L, 301L, 325L, 349L, 373L, 397L, 421L, 434L, 422L, 424L, 429L, 
435L, 146761L), Var1_type = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L), .Label = c("imputed", 
"observed"), class = "factor"), Var2_type = structure(c(1L, 1L, 
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 
2L, 1L), .Label = c("imputed", "observed"), class = "factor")), class = "data.frame", row.names = c(NA, 
-20L))

but instead of 2 countries, I have 194 countries .

I would like to plot charts on multiple pages and export in pdf. I have used the code below but it runs forever and never exports anything... what am I doing wrong?

plist <- lapply(split(df, df$iso3), function(d) {
df %>% 
  pivot_longer(cols = -c(iso3, year, Var1, Var2),  
               names_to = c("group", ".value"), 
               names_pattern = "(.*)_(.*)") %>%   
  ggplot(aes(x=year, y=imp, shape = type, colour=group)) + 
  geom_line(aes(group = group, colour = group), size = 0.5) +
  geom_point(aes(group = group, colour = group, shape = type),size=2)  +
  scale_shape_manual(values = c('imputed' = 21, 'observed' = 16)) + 
  facet_wrap(iso3~., scales = "free") + xlab("Year") + ylab("Imp")
})


plots <- marrangeGrob(plist, nrow = 4, ncol = 3)

ggsave("multipage.pdf", plots, width = 11, height = 8.5, units = "in")

Thanks!

Saving plots over multiple pages of a pdf is done most easily using pdf() / dev.off() and print() rather than ggsave() for me. Either of the following should give you a multipage pdf:

# print the list directly
pdf("myplots.pdf")
print(plist)
dev.off()

# print the grob
pdf("myplotsgrob.pdf")
print(plots)
dev.off()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM