我有一个有 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
vscyl
,然后是mpg
vsvs
,然后是mpg
vsam
,在同一页面上生成 3 个不同的图。
我的代码(灵感来自使用for循环和grid.range和ggplot2在一页上的多个ggplots:使用循环在一页中打印多个绘图(:
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"
规范的方式是分面:
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)