r - plotting means, errors, and then raw data in background - simpler code? -


i want plot mean , standard error of continuous variable, grouped categorical 1 in r. want in background have actual raw data points went in generating mean , standard error. resulting plot this:

enter image description here

i coded myself, requires multiple custom functions (for generating standard error, group means), adding things data frame generate jitter , around graphics hiccups. code copied here , generate necessary data:

##generate 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 , 2s correspond treatment plotting later. niormal distribution allows me jitter points along 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 function 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 function grab data frame, , kick means , standard errors 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 plotting 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 mean , 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) 

this ton of code make 1 figure! there simpler way this- either without cstom functions, or using ggplot?

you can less code in 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)  

(updated per @roland's comment: 1 standard error equivalent confidence interval of 68.3%.)

enter image description here


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -