我想要ggplot
与facet_wrap
的多个因素包含以下数据:
set.seed(1)
df <- data.frame(sample=c("c0.A_1","c0.A_2","c1.A_1","c1.A_2","c2.A_1","c2.A_2","c0.B_1","c0.B_2","c1.B_1","c1.B_2","c2.B_1","c2.B_2"),
replicate=rep(c(1,2),6),val=vals,min.val=min.vals,low.val=low.vals,max.val=max.vals,high.val=high.vals,
group=c(rep("A",6),rep("B",6)),cycle=rep(c("c0","c0","c1","c1","c2","c2"),2),
stringsAsFactors = F)
facet.factors <- c("group","cycle")
for(f in 1:length(facet.factors)) df[,facet.factors[f]] <- factor(df[,facet.factors[f]],levels=unique(df[,facet.factors[f]]))
在这种情况下,我有2个分面因素,但这可能会有更多。
以下是我创建分面公式的一般方法:
levels.vec <- sapply(facet.factors,function(f) length(levels(df[,f])))
df$col.fill <- Reduce(function(...) paste(..., sep = ":"), df[,facet.factors])
df$col.fill <- factor(df$col.fill,levels=unique(df$col.fill))
facet.formula <- as.formula(paste('~',paste(facet.factors,collapse='+')))
绘图给了我这个:
require(ggplot2)
ggplot(df,aes_string(x="replicate",ymin="min.val",lower="low.val",middle="val",upper="high.val",ymax="max.val",col=facet.factors,fill=facet.factors))+
geom_boxplot(position=position_dodge(width=0),alpha=0.5,stat="identity")+
facet_wrap(facet.formula,ncol=max(levels.vec))+
labs(x="Replicate",y="Val")+
scale_x_continuous(breaks=unique(df$replicate))+
theme_bw()+theme(legend.position="none",panel.border=element_blank(),strip.background=element_blank(),axis.title=element_text(size=8))
facet_wrap用每个级别之间的新行分隔标签。有办法改变吗?用自定义分隔符分开?