我正在尝试在一张图中绘制多个不同的ggplots(请参见下面的代码)。
我认为应该这样做:
library(ggplot2)
library(Rmisc)
set.seed(1)
y <- rnorm(12,0,1)
df <- data.frame(y=rep(y,3),age=rnorm(12,50,2),sex=c(rep("female",6),rep("male",6)),race=c(rep("black",3),rep("white",3),rep("other",3)))
df$sex <- as.factor(df$sex)
df$race <- as.factor(df$race)
covariates = c("age","sex","race")
ggplot_list <- vector(mode="list", length(covariates))
for(i in 1:length(covariates)){
if(is.factor(df[,covariates[i]])){
ggplot_list[[i]] <- ggplot(df, aes(x=df[,covariates[i]], y=df$y), environment = environment())+geom_boxplot()+geom_jitter()+labs(x = covariates[i],y="y")
} else{
ggplot_list[[i]] <- ggplot(df, aes(x=df[,covariates[i]], y=df$y), environment = environment())+geom_point(shape=1)+labs(x = covs[i],y="y")
}
}
但:
multiplot(plotlist=ggplot_list,cols=length(covariates))
帮助..
在内部,aes
您仅应引用列名称,而不要同时包含数据框名称和列名称。您已经将数据框传递到ggplot
(ggplot(df,...)
)中,因此ggplot
已经可以访问其环境中的数据框列。aes
通过告诉ggplot进入该数据帧的父环境,可以将数据帧包含在内,从而颠覆了这一点。这是您的代码版本,可以完成您想要的功能。我们使用aes_string
代替,aes
以便我们可以将covariates
as的值传递为字符串:
ggplot_list <- vector(mode="list", length(covariates))
for(i in 1:length(covariates)){
if(is.factor(df[,covariates[i]])){
ggplot_list[[i]] <- ggplot(df, aes_string(x=covariates[i], y="y")) +
geom_boxplot() +
geom_jitter() +
labs(x = covariates[i], y="y")
} else{
ggplot_list[[i]] <- ggplot(df, aes_string(x=covariates[i], y="y")) +
geom_point(shape=1) +
labs(x = covariates[i],y="y")
}
}
这是一个更简洁的版本:
# List to store plots
pl = list()
for (i in covariates) {
# Set up parts of plot that don't change
pl[[i]] = ggplot(df, aes_string(x=i, y="y")) + labs(x = i)
# Different handling for categorical and numeric x variable
if (is.numeric(df[,i])) {
pl[[i]] = pl[[i]] + geom_point(shape=1)
} else {
pl[[i]] = pl[[i]] + geom_boxplot() + geom_jitter(width=0.2)
}
}
您也可以使用lapply
而不是for循环来执行此操作:
pl = lapply(covariates, function(cc) {
# Set up parts of plot that don't change
p = ggplot(df, aes_string(x=cc, y="y")) + labs(x = cc)
# Different handling for categorical and numeric x variable
if (is.numeric(df[, cc])) {
p = p + geom_point(shape=1)
} else {
p = p + geom_boxplot() + geom_jitter(width=0.2)
}
})
来布置图,使用grid.arrange
从gridExtra
包(plot_grid
从cowplot
是另一种选择,如通过@JoshuaRosenberg指出):
library(gridExtra)
grid.arrange(grobs=pl, ncol=length(covariates))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句