ggplot-在多个页面上绘制图表

时间:2020-05-19 07:27:51

标签: ggplot2 lapply

我的数据集如下:

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))

我有 194个国家,而不是2个国家/地区。

我想在多页上绘制图表并以pdf格式导出。我使用了下面的代码,但是它可以永远运行并且永远不会导出任何内容……我在做什么错了?

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")

谢谢!

1 个答案:

答案 0 :(得分:0)

对于我来说,使用pdf() / dev.off()print()ggsave()而不是# print the list directly pdf("myplots.pdf") print(plist) dev.off() # print the grob pdf("myplotsgrob.pdf") print(plots) dev.off() 最容易完成在pdf的多页上保存图的工作。以下任何一种都应为您提供多页pdf:

sudo apt-get install flac