同一页PDF上显示多个R ggplot图表

4

我有一个包含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循环,我想绘制mpgcyl的图形,然后是mpgvs的图形,最后是mpgam的图形,在同一页上生成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]] - Axeman
True。Roland 在下面的代码中包含了它。 - user31888
1个回答

4

最常用的方法是进行facet(分类):

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"),但文件中只有最后一个图而不是三个图? - user31888
你不能使用ggsave与第二种方法。你必须使用pdf - Roland
我似乎漏掉了什么。我在for循环之前放置了pdf("My_3_plots.pdf"),并在do.call之后放置了dev.off(),但生成的PDF文件是空白的(我可以无误地打开它)。 - user31888
多次调用 dev.off() 直到出现 Error in dev.off() : cannot shut down device 1 (the null device) 错误,然后再尝试。在 do.call 前可以加上 pdf("My_3_plots.pdf") - Roland

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接