Creating a barplot from csv file

Viewed 34

I'm trying to accomplish a pretty simple task but I am really struggling to achieve what I want. I created a csv file for my data set and am now trying to import it into R and create a barplot from it. This is what the data set looks like.

control salted unsalted
3 12 23
7 15 25
4 13 20
2 17 18

From this, I want to create an error bar chart but I can't figure out how to make it work. I don't think I should need a package for this but am I mistaken?

This is an example of what I want to do.

As I said, it's pretty simple but I've reached the point where I have to throw in the towel and accept that I won't manage it on my own. Any and all advice welcome! Thank you

2 Answers

Not quite so simple as we might hope. Adding error bars to barplots isn't a default in R (likely because they are known to be a problematic visualization type) so we have to build the plot up almost from scratch.

# Create the data within R
dat <- data.frame(
  control=c(3, 7, 4, 2),
  salted=c(12, 15, 13, 17),
  unsalted=c(23, 25, 20, 18)
)
# Calculate mean and SD for each treatment
treatment_means <- sapply(dat, mean)
treatment_sds <- sapply(dat, sd)
# Create a blank plot with type = "n"
# Specify x and y limits
# Use factor(names(treatment_means)) to give each bar a name
plot(factor(names(treatment_means)), treatment_means, type = "n", 
     xlim = c(0.5, 3.5), ylim=c(0, 30))
# Add the bars themselves using rect() with a width of +/-0.4 plot units
rect(xleft = 1:3-0.4, xright = 1:3+0.4, ybottom = 0, 
     ytop = treatment_means, col="grey50")
# Redraw the box around the plot since the rectangles overlap it
box()
# Finally, add the error bars using arrows() with code=3 and angle=90
# to create "flat" heads on both ends
# pmax(0, ) prevents the bars from going negative
arrows(x0 = 1:3, x1 = 1:3, y0 = treatment_means-treatment_sds, 
       y1=treatment_means+treatment_sds, angle = 90, code = 3)

which produces

barplot, as requested

barplot returns the x coordinates of bar midpoints so you can use these to add other stuff to the plot using e.g. segments:

# borrowed from Dubukay's answer
dat <- data.frame(
  control=c(3, 7, 4, 2),
  salted=c(12, 15, 13, 17),
  unsalted=c(23, 25, 20, 18)
)

# calculate mean and SD for each treatment
means <- sapply(dat, mean)
sds <- sapply(dat, sd)

bp <- barplot(means, ylim=c(0, max(means + sds)))
# vertical lines
segments(bp, means - sds, y1=means + sds)
# horizontal bars
bar.wd <- .3
segments(rep(bp, 2) - bar.wd/2, 
         means + c(-sds, sds), 
         rep(bp, 2) + bar.wd/2)

Barplot with error bars

Related