2016-10-23 3 views
1

と並んでggplot2 geom_boxplot側に私はこれらのデータを持っている:

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たい - 上部の2つのファセットがあること、それらがそのようなgeom_boxplotdf$group == xと下部にはdf$group == yされています、各面でがdf$side == 2の左側に表示されます。私はまた、df$group == xdarkgraydf$group == ydarkredの色にしたいと思います。

は、ここで私が試したものです:

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は私を与える:df$side == 2の左にdf$side == 1を持っていない以外は近い enter image description here

どうすればいいですか?

+0

ggplot(df、aes(side、color = group))は正しく出力されていますか? – mtoto

+0

残念なことに、いいえ – dan

+1

予想される出力がどのようになるかを詳しく説明できますか? – mtoto

答えて

1

私はそれは(あなたもside:nameを使用することができます)引数のレベルのすべての組み合わせに基づいて係数を作成するためにinteractionを使用して、これはあなたが後にしているものかもしれないと思う:

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