【发布时间】: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.arrange 和 ggplot2 : 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 将其包含在下面的代码中