我有一個data.frame
我想ggplot
與facets
:從ggplot面卸下來港標籤
library(dplyr)
set.seed(1)
samples <- c("mt1.2m_1","mt1.2m_2","mt1.4m_1","mt1.4m_2","mt1.4m_3","mt1.4m_4","mt1.4m_5","mt1.6m_1","mt1.6m_2","mt1.6m_3","mt1.6m_4","mt1.6m_5",
"mt2.2m_1","mt2.2m_2","mt2.4m_1","mt2.4m_2","mt2.6m_1","mt2.6m_2",
"wt.2m_1","wt.2m_2","wt.2m_3","wt.2m_4","wt.2m_1","wt.4m_2","wt.4m_3","wt.4m_4","wt.6m_1","wt.6m_2","wt.6m_3","wt.6m_4")
val <- rnorm(30)
df <- data.frame(sample=samples,val=rnorm(length(samples)),gt2m=NA,gt4m=NA,gt6m=NA,stringsAsFactors=F)
df$replicate <- as.integer(gsub("^.*_","",df$sample,perl=T))
df$gt2m[which(grepl("2m_",df$sample))] <- gsub("_\\d+$","",df$sample[which(grepl("2m_",df$sample))],perl=T)
df$gt4m[which(grepl("4m_",df$sample))] <- gsub("_\\d+$","",df$sample[which(grepl("4m_",df$sample))],perl=T)
df$gt6m[which(grepl("6m_",df$sample))] <- gsub("_\\d+$","",df$sample[which(grepl("6m_",df$sample))],perl=T)
df$gt2m <- factor(df$gt2m,levels=c("mt1.2m","mt2.2m","wt.2m"))
df$gt4m <- factor(df$gt4m,levels=c("mt1.4m","mt2.4m","wt.4m"))
df$gt6m <- factor(df$gt6m,levels=c("mt1.6m","mt2.6m","wt.6m"))
#add error bar values
val.error <- 0.05*mean(abs(df$val))
df$min.val <- df$val-3*val.error
df$low.val <- df$val-val.error
df$max.val <- df$val+3*val.error
df$high.val <- df$val+val.error
#add a factor to color by
df$col.fill <- factor(apply(dplyr::select(df,gt2m,gt4m,gt6m),1,function(x) x[which(!is.na(x))]))
我想小面由gt2m
,gt4m
和gt6m
列情節 - 這是稀疏。我定義了一個forumla
爲:
facet.formula <- as.formula("~gt2m+gt4m+gt6m")
這裏是我怎樣,我想要繪製此:
這是除了NA
S IN近乎完美facet
標籤。
我想:
ggplot(df,aes(x=replicate,ymin=min.val,lower=low.val,middle=val,upper=high.val,ymax=max.val,col=col.fill,fill=col.fill))+
geom_boxplot(position=position_dodge(width=0),alpha=0.5,stat="identity")+
facet_wrap(scales="free_x",facet.formula,ncol=length(levels(df$col.fill)),labeller = function (labels) {
labels <- lapply(labels, as.character)
list(do.call(paste, c(labels[which(labels != "NA")], list(sep = ":"))))})
但給出相同的結果。
任何想法如何從facet
標籤中刪除這些NA
s?
這不是預期的輸出? 'ggplot(df,aes(x = replicate,ymin = min.val,lower = low.val,middle = val,upper = high.val,ymax = max.val,col = col.fill))+ geom_boxplot( stat =「identity」,alpha = 0.5)+ facet_grid(〜col.fill)' – Jimbou
你是對的。 facet_grid解決它。謝謝 – dan