Building tools, errors, and then background data in the background - simpler code?

I want to build the mean and standard error of a continuous variable grouped categorical in R. Then I want the background to have the actual data source points that came to create this average and standard error. The resulting plot will look like this:

enter image description here

I encoded this myself, but this requires several user-defined functions (to generate a standard error, group tools), as well as adding some things to the data frame to generate jitter and bypass some graphic hiccups. Here the code is copied and generates all the necessary data:

##generate some fake data###
ctrl<- rnorm(20,1,0.5)
treated<- rnorm(20,2,0.5)
ctrl.lab<- rep('ctrl',20)
treated.lab<- rep('treated',20)
#adding 1s and 2s that correspond to treatment for plotting later. The niormal distribution allows me to jitter the points along the y-axis
ctrl.alt<- rnorm(20,1,0.02) 
treated.alt<- rnorm(20,2,0.02)
alt<-c(ctrl.alt,treated.alt) later
lab<-c(ctrl.lab,treated.lab)
response<- c(ctrl,treated)

data<-data.frame(lab,response,alt)

#make a function for plotting error bars
errb <- function (x, y, ebl, ebu = ebl, length = 0.06, ...){
  arrows(x, y + ebu, x, y - ebl, angle = 90, code = 3,
  length = length, ...)
  }
#make a function that will grab a data frame, and kick back means and standard errors by a grouping variable. 
meanerr<- function(data,param,grouping){
    means<-aggregate(param~grouping,data=data,FUN=mean)
    sd<-aggregate(param~grouping,data=data,FUN=sd)
    count<-aggregate(param~grouping,data=data,FUN=length)
    err<-sd$param/sqrt(count$param)
    output<-cbind(means,err)
    return(output)
}  

d3<-meanerr(data,data$response,data$lab)
d3$alt<-c(1,2) #for plotting. 
limx<-c(0.6,2.4) #set x limits
limy<-c(0,3.1) #set y limits

#start with plotting the jittered raw data points. 
plot(data$alt,data$response,
    pch=16,
    xaxt='n',
    ylab=NA,
    xlab='',
    xlim=limx,
    ylim=limy,
    col='light gray')
par(new=T)
#now add the mean and standard error
plot(d3$alt,d3$param,
    pch=16,
    xaxt='n',
    ylab=NA,
    xlab='',
    cex=2,
    xlim=limx,
    ylim=limy,
    col='black')
    axis(1,at=1:2, labels=d3$grouping,cex.axis=1.4)
    mtext('response',2,cex=1,line=2)
    errb(d3$alt,d3$param,d3$err,col='black',cex=2)

, ! - cstom, ggplot?

+4
1

ggplot2:

library(ggplot2)

ggplot(data, aes(lab, response)) +
  geom_point(alpha=0.3, position=position_jitter(height=0, width=0.05)) +
  stat_summary(fun.data=mean_cl_normal, geom="errorbar", 
               width=0.03, colour="red", alpha=0.7, conf.int=.683) +
  stat_summary(fun.y=mean, geom="point", fill="red", pch=21, size=3) 

( @Roland: 68,3%.)

enter image description here

+5

All Articles