I am having problems generating a ggplot.
My plot is a simple box plot but with additional annotations.
Those annotations are the significance levels of multiple comparisons.
This is better explained by DatamineR here: How to draw the boxplot with significant level?
I only want to plot those that are significantly different and want the function to be robust.
So to make it stupid simple I just want to add X
lines to a ggplot
example:
custom.plot <- function{
n.sig <- number of significant observations obtained by a different function
my.plot <- ggplot(data,aes(x,y)) + geom_boxplot()
### HERE should be a function that adds other layers to my plot
}
How can I now make a function that will add n.sig
lines to my plot?
n.sig = 3
would mean the following:
my.plot +
geom_line(data1,aes(x1,y1))+
geom_line(data2,aes(x2,y2))+
geom_line(data3,aes(x3,y3))
I already have all the data frames for my geom_line
functions and I figured out that I can create a function call using this function
do.call("geom_line",list("data1","aes(x1,y1)")
but how can I then make this into one big function call for ggplot
?
In other words I want this function that I wrote for base plot to work in ggplot2:
all.f <-function(x,y){
boxplot(data[,y]~data[,x],ylab=y,xlab="")
dt <- dunn.test(data[,y],data[,x],method="bonferroni")
### Split outcome by group
out.sp <- split(data[,y],data[,x])
len.vars <- sapply(out.sp,length)
len.all <- length(len.vars)
imp.dt<-which(dt$P.adjusted<0.05)
check.pairs <- function(x){
if(x==1){
return(cbind(1,2))
}else if(x==2){
return(cbind(1,3))
}else if(x==3){
return(cbind(2,3))
}else if(x==4){
return(cbind(1,4))
}else if(x==5){
return(cbind(2,4))
}else if(x==6){
return(cbind(3,4))
}else if(x==7){
return(cbind(1,5))
}else if(x==8){
return(cbind(2,5))
}else if(x==9){
return(cbind(3,5))
}else if(x==10){
return(cbind(4,5))
}else{
return(NA)
}
}
connections <- sapply(imp.dt,check.pairs)
n.connections <- length(imp.dt)
df.con <- list(NULL)
my <-max(data[,y],na.rm=T)
cord <- NULL
for(i in 1:n.connections){
cord <- c(cord,my-((0+i)*my*0.03))
}
connect<-matrix(rbind(connections,cord),nrow=3)
boxplot(data[,y]~data[,x],ylab=y,xlab="")
if(!n.connections==0){
for(i in 1:n.connections){
segments(connect[1,i],connect[3,i],connect[2,i],connect[3,i])
}
} else {
NULL
}
}
run it on mtcars:
data<-mtcars
data$cyl<-as.factor(data$cyl)
all.f("cyl","mpg")