如何使用 for 函数在 R 中构造 ggplot2 图的面板



我是一个初学者,试图在ggplot2中构建多个图。在 R 中使用 mtcars 数据集

library(datasets)
data (mtcars)
library (ggplot2)
## convert to factor some variables to avoid problems
factors<-c(2,9,10,11)
mtcars[,factors]<-lapply(mtcars[,factors],factor)

我想绘制 mpg 与所有其他变量,除了在每个图中以颜色绘制的 am 变量。每个图如下所示:

g1<- ggplot(mtcars, aes(x=mpg, y=cyl, color=am)) + geom_point(shape=1)
g2<- ggplot(mtcars, aes(x=mpg, y=disp, color=am)) + geom_point(shape=1)
g3...

只有一个图的 y 轴从图更改为另一个图。我已经完成了从 g1 到 g9 的图,y 轴是以下任何一种:

variables<- c ("cyl","disp","hp","drat","wt","qsec","vs","gear","carb") 

我相信一定有更优雅的方式来生成所有 9 个图,但无法弄清楚有什么帮助吗?

如果你想在g1...g_n

g <- lapply(variables, function(var) {
  ggplot(mtcars, aes_string(x="mpg", y=var, color="am")) + geom_point(shape=1) 
})
names(g) <- paste0("g", seq(g))
list2env(g, .GlobalEnv)

最新更新