I have a data.frame
I'd like to ggplot
with facets
:
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))]))
I want to facet the plot by the gt2m
, gt4m
, and gt6m
columns - which are sparse. I define a forumla
for that:
facet.formula <- as.formula("~gt2m+gt4m+gt6m")
Here's how I'm trying to plot this:
library(ggplot2)
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, list(sep = ":"))))})
That's almost perfect except for the NA
s in the facet
labels.
I tried:
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 = ":"))))})
But that gives the same result.
Any idea how to delete these NA
s from the facet
labels?
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)
– Roman