【问题标题】:Multiple R ggplots on same pdf page同一pdf页面上的多个R ggplots
【发布时间】:2018-05-16 12:41:07
【问题描述】:

我有一个包含 4 列的输入数据框。

test <- head(mtcars[,c(1,2,8,9)])
test
                   mpg cyl vs am
Mazda RX4         21.0   6  0  1
Mazda RX4 Wag     21.0   6  0  1
Datsun 710        22.8   4  1  1
Hornet 4 Drive    21.4   6  1  0
Hornet Sportabout 18.7   8  0  0
Valiant           18.1   6  1  0

使用 for 循环,我想绘制 mpg vs cyl,然后是 mpg vs vs,然后是 mpg vs am,在同一页面上生成 3 个不同的图。

我的代码(灵感来自 Multiple ggplots on one page using a for loop and grid.arrangeggplot2 : printing multiple plots in one page with a loop):

library(ggplot2)
library(gridExtras)

plot_list <- list()
for(i in 2:ncol(test)){
   plot_list[[i]] <- ggplot(test, aes(x=test[,i], y=mpg, fill=test[,i])) + 
   geom_point()
}
grid.arrange(grobs=plot_list)

输出:

Error in gList(list(wrapvp = list(x = 0.5, y = 0.5, width = 1, height = 1,  :
  only 'grobs' allowed in "gList"

【问题讨论】:

  • plot_list 的第一个元素为空 (NULL)。你需要写信给plot_list[[i - 1]]
  • 是的。 Roland 将其包含在下面的代码中

标签: r ggplot2 grob


【解决方案1】:

规范的方法是刻面:

test <- head(mtcars[,c(1,2,8,9)])
library(reshape2)
test <- melt(test, id.vars = "mpg")
library(ggplot2)
ggplot(test, aes(x = value, y = mpg, fill = value)) +
  geom_point() +
  facet_wrap(~ variable, ncol = 1)

如果你准备好了:

library(gridExtra)
plot_list <- list()
test <- head(mtcars[,c(1,2,8,9)])
for(i in 2:ncol(test)){
    plot_list[[i-1]] <- ggplotGrob(ggplot(test, aes(x=test[,i], y=mpg, fill=test[,i])) + 
    geom_point())
}
do.call(grid.arrange, plot_list)

【讨论】:

  • 有效!在geom_point() 之后缺少一个括号。另外,为什么当我在do.call() 之后调用ggsave("my_plot.pdf") 时,我只得到文件中的最后一个图而不是3?
  • 第二种方法不能使用ggsave。您必须使用pdf
  • 我遗漏了一些东西。我把pdf("My_3_plots.pdf")放在for loop之前,dev.off()放在do.call之后,但是生成的pdf文件是空白的(我可以毫无错误地打开它)。
  • 多次致电dev.off(),直到您收到Error in dev.off() : cannot shut down device 1 (the null device),然后重试。您可以将pdf("My_3_plots.pdf") 放在do.call 之前。
猜你喜欢
  • 2021-12-19
  • 2018-07-14
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
相关资源
最近更新 更多