0

I am trying to add error bars to my barplot

averg <- aggregate(appxincome,by = list(educ,sex),mean)              
boxplot1 <- barplot(averg$x,
                xlab = "Education",
                ylab = "Income",
                ylim = c(0,100000),

                main = "Averge Income by Education and Gender",
                names.arg = c("Female College", "Female High      School","Female Less Than High School","Male College", "Male High      School","Male Less Than High School"),
                cex.names = 0.5,
                las = 2)                                        
confint(mod1)    

cis <- as.data.frame(confint(mod1)) 

error.bar <- function(x, y, upper, lower=upper, length=0.1,...){
  if(length(x) != length(y) | length(y) !=length(lower) | length(lower) != 
length(upper))
    stop("vectors must be same length")
  arrows(x,y+upper, x, y-lower, angle=90, code=3, length=length, ...)
}

stdevs<-aggregate(appxincome~sex,FUN=sd)
lengths<-aggregate(appxincome~sex,FUN=length)
error.bar(boxplot1,averg[,2], 1.96*stdevs[,2]/lengths[,2])

I am getting an error message about the vector length. Can somebody help me fix this? thanks

Richard Telford
  • 9,558
  • 6
  • 38
  • 51
  • 2
    Please provide [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) when you're asking a question. – Adam Quek Apr 17 '17 at 02:44

1 Answers1

0

Here's how you do a simple ANOVA plot using ggplot.

Take a linear model example displ ~ class for mpg data.

mod <- lm(displ ~ class, data=mpg)

Build up the fit and confidence interval for each class:

newdat <- data.frame(class=levels(as.factor(mpg$class)))

newdat$fit <- predict(mod, newdat)
newdat$SE <- predict(mod, newdat, se.fit=TRUE)[[2]]

newdat$upp <- newdat$fit + 1.96*newdat$SE
newdat$lwr <- newdat$fit - 1.96*newdat$SE

newdat
       class      fit        SE      upp      lwr
1    2seater 6.160000 0.3822334 6.909177 5.410823
2    compact 2.325532 0.1246708 2.569887 2.081177
3    midsize 2.921951 0.1334817 3.183575 2.660327
4    minivan 3.390909 0.2577017 3.896004 2.885814
5     pickup 4.418182 0.1487842 4.709799 4.126565
6 subcompact 2.660000 0.1444707 2.943162 2.376838
7        suv 4.456452 0.1085470 4.669204 4.243700

Plot barplot and errorbar with ggplot:

library(ggplot2)
ggplot(newdat, aes(x=class, y=fit)) + 
      geom_bar(stat="identity") + 
      geom_errorbar(aes(ymin=lwr, ymax=upp))

enter image description here

Adam Quek
  • 6,973
  • 1
  • 17
  • 23
  • For my problem, I have to create the graph displays mean income by sex and education. When I first created my linear model, I made it mod1 <- lm(appxincome~sex*educ). How would I fix it to work with your code? – Michael Rubino Apr 18 '17 at 14:46
  • Please provide [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) when you're asking a question. – Adam Quek Apr 19 '17 at 03:56