ggplot2 geom_boxplot与facet并排

时间:2016-10-23 08:17:51

标签: r ggplot2 facet

我有这些数据:

set.seed(1)
df <- data.frame(y=rnorm(12),name=factor(rep(c("a","a","b","b","c","c"),2),levels=c("a","b","c")),side=factor(rep(1:2,6),levels=1:2),group=factor(c(rep("x",6),rep("y",6)),levels=c("x","y")),stringsAsFactors=F)
df$upper <- df$y+0.1*df$y
df$lower <- df$y-0.1*df$y
df$max <- df$y+0.25*df$y
df$min <- df$y-0.25*df$y

我希望ggplot - geom_boxplot他们有两个方面,最上面是df$group == x,下方是df$group == y,其中每个方面df$side == 1出现在df$side == 2的左侧。我还要为df$group == x darkgraydf$group == y darkred着色。

以下是我尝试的内容:

library(ggplot2)
p <- ggplot(data=df,aes(name,color=group))+facet_wrap(~group,ncol=1)+scale_color_manual(values=c("darkgray","darkred"),labels=levels(df$group),name="group")+scale_fill_manual(values=c("darkgray","darkred"),labels=levels(df$group),name="group")
p <- p+geom_boxplot(aes(fill=group,lower=lower,upper=upper,middle=y,ymin=min,ymax=max),position=position_dodge(width=0),alpha=0.5,stat="identity")+theme(text=element_text(size=10))
p <- p+guides(fill=guide_legend(reverse=FALSE),colour=guide_legend(reverse=FALSE))

p给了我: enter image description here

除了df$side == 1左侧没有df$side == 2外,它已接近。

知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

我认为这可能是你所追求的,它使用interaction根据其参数级别的所有组合创建一个因子(你也可以使用side:name):

ggplot(df, aes(x=name, group=interaction(side, name),
               col=group, fill=group)) +
    facet_wrap(~group) +
    geom_boxplot(aes(lower = lower, upper = upper,
      middle = y, ymin = min, ymax = max),
      position = position_dodge(width = 0.5),
      alpha = 0.5, stat = "identity")

enter image description here

可能更清楚的是使用颜色来显示哪一面是哪一面,因为正面已标注该组:

ggplot(df, aes(x=name, group=interaction(side, name),
               col=side, fill=side)) +
    facet_wrap(~group) +
    geom_boxplot(aes(lower = lower, upper = upper,
      middle = y, ymin = min, ymax = max),
      position = position_dodge(width = 0.5),
      alpha = 0.5, stat = "identity")

enter image description here