R语言 用循环绘制每列的ggplots并保存为pdf

fcy6dtqo  于 2023-04-27  发布在  其他
关注(0)|答案(3)|浏览(170)

我有149个系列,我想绘制成一个线图(年作为x轴),这些应该在pdf中自动生成,理想情况下在一页上有4个图。目前我只能用普通的plot函数来完成,ggplot也可以吗?所以它可以很好地与普通图一起工作:

dfMA <- structure(list(year = c(2000:2005),a = c(0.2569, 0.0145896,
0.0369, 0.025986, 0.12569, 
                           0.3695), b = c(0.125, 0.04582, 0.2569, 0.256369, 0.25698, 0.1456
                           ), c = c(0.2584, 0.05698, 0.1258, 0.2569, 0.098563, 0.1569)), row.names = c(NA,-6L), class = "data.frame")

pdf("test.pdf")
par(mfrow=c(2,2))

invisible(lapply(colnames(dfMA),function(x){
  plot(dfMA$year, dfMA[,x],main=x,type="l",xaxt="n", ylab = "Ring width [mm]", xlab = "", ylim=c(0,0.8)) + grid(nx = NULL, ny = NULL,lty = 2, col = "gray", lwd = 2) + axis(1, at = seq(1985, 2019, by = 2), las=2)
}))

dev.off()

不幸的是,当我尝试将不可见函数适应ggplot时,它不起作用。

invisible(lapply(colnames(dfMA),function(x){
  ggplot(dfMA, aes(x=i, y = year)) + ggarrange(ncol=2,nrow=2) + geom_line() + print() 
         }))
siv3szwd

siv3szwd1#

不需要invisible。此外,在使用ggarrange将它们粘合在一起之前,您必须首先创建图并将其存储在列表中。最后,我使用.data代词将列名(字符串)Map到y美学上:

library(ggpubr)

pdf("test.pdf")
plots <- lapply(colnames(dfMA), function(x) {
  ggplot(dfMA, aes(x = year, y = .data[[x]])) +
    geom_line() +
    scale_y_continuous(limits = c(0, 0.8)) +
    labs(y = "Ring width [mm]", title = x)
})
ggarrange(plotlist = plots, ncol = 2, nrow = 2) 
dev.off()

tktrz96b

tktrz96b2#

以下是tidyverse方法:

library(tidyverse)

plots <- dfMA %>% 
  pivot_longer(-year, names_to = "variable", values_to = "value") %>% 
  group_by(variable) %>% 
  nest() %>% 
  mutate(plot = map(data, ~ggplot(.x, aes(x = year, y = value)) +
                      geom_line() +
                      ylab("Ring width [mm]") +
                      xlab("Year") +
                      scale_x_continuous(limits = c(2000, 2005), breaks = seq(2000, 2005, 1), expand = c(0, 0)) +
                      scale_y_continuous(limits = c(0, 0.8), breaks = seq(0, 0.8, 0.1), expand = c(0, 0)) +
                      ggtitle(""))) %>% 
  pull(plot)

# Save the plots
pdf("plots.pdf", width = 8.5, height = 11)
gridExtra::grid.arrange(grobs = plots, ncol = 2, nrow = 2)
dev.off()

68bkxrlz

68bkxrlz3#

我用ggsave做的
试试这个

library(ggplot2)
    
    for (col in colnames(dfMA)[-1]) {
      p <- ggplot(dfMA, aes(x = year, y = get(col))) + 
        geom_line() + 
        labs(title = col)

  
  ggsave(paste0(col, ".pdf"), p, device = "pdf")
}

相关问题