在一个图中绘制多种不同类型的ggplots

时间:2016-05-14 19:37:29

标签: r ggplot2

我正在尝试在一个图表中绘制多个不同的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

2 个答案:

答案 0 :(得分:1)

aes内,您应该只引用列名,而不是同时包含数据框名称和列名。您已将数据框传递到ggplotggplot(df,...)),因此ggplot已经可以访问其环境中的数据框列。通过告诉ggplot进入数据框的父环境,将aes内的数据框包括在内。这是您的代码版本,可以执行您想要的内容。我们使用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.arrange包中的gridExtraplot_grid cowplot是另一种选择,正如@JoshuaRosenberg所指出的那样:

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

enter image description here

答案 1 :(得分:0)

尝试cowplot(小插图here)。

获得ggplot个对象之后,如:

plot_grid(plot_age, plot_gender, plot_race)