2016-05-14 101 views
1

我試圖在一個圖中繪製多個不同的ggplots(請參閱下面的代碼)。在一個圖中繪製多個不同類型的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)) 

幫助..

給出: enter image description here

回答

1

裏面aes你應該僅指列名,而不是包括數據幀名和列名。您已將數據幀傳遞到ggplotggplot(df,...)),因此ggplot已有權訪問其環境中的數據幀列。在aes中包含數據幀通過告訴ggplot進入數據框的父環境之外來破壞數據幀。這是你的代碼的一個版本,它看起來像你想要的。我們使用aes_string代替aes這樣我們就可以通過的covariates的值作爲字符串:

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.arrangegridExtra包(plot_gridcowplot是另一種選擇,如通過@JoshuaRosenberg指出):

library(gridExtra) 
grid.arrange(grobs=pl, ncol=length(covariates)) 

enter image description here

0

嘗試cowplot(暗角here)。

一旦你的ggplot對象,像:

plot_grid(plot_age, plot_gender, plot_race)

相關問題