2016-05-14 7 views
1

複数の異なるggplot(以下のコードを参照)を1つのグラフにプロットしようとしています。複数の異なる種類のggplotsを1つのグラフにプロットする

私は、これはそれを行うべきと思った:

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

をあなたが唯一のデータフレーム名とカラム名の両方を含む列名ではなく、を参照してください。 ggplotggplot(df,...))に既にデータフレームを渡していますので、ggplotは既にその環境内のデータフレーム列にアクセスできます。 aesの中のデータフレームを含むことは、ggplotにデータフレームの親環境の外に出るように伝えることによって、それを覆します。ここに、あなたが望むように見えるようにするコードのバージョンがあります。

ここ
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") 
    } 
} 

は、より簡潔なバージョンです:私たちは文字列としてcovariatesの値を渡すことができるように私たちは、代わりにaesaes_stringを使用

# 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) 
    } 
} 

また、代わりに、forループのlapplyでこれを行うことができます:

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を使用するには0パッケージ(@JoshuaRosenbergによって指摘されるようcowplotからplot_gridは、別のオプションである):

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

enter image description here

0

cowplot(ビネットhere)を試してみてください。

あなたがggplotオブジェクト、何かしたら:aesインサイド

plot_grid(plot_age, plot_gender, plot_race)

関連する問題