Wednesday, 8 April 2015

Looping through a data frame to make graphs with error bars...

Inspired by Jo Welton, I have written an R script to allow me to loop through and make lots of histograms with error bars.

The following links were useful in working all this out:



The data is arranged in rows with the name of the protein on the left and with means and SDs of two different groups in the data frame.


File called sampleData.csv



I have written a script that produces these graphs in one output.


Here is the script:

# I used the Excel file to create a csv file that I then imported into R. 
data <- read.csv("sampleData.csv")
#This creates a data frame.
str(data)

#Based on the data frame:
#create a vector m, with the data in it 
m<-c(data[1,2], data[1,3])
#then draw a bar plot
barplot(m, horiz=TRUE, 
        main = data[1,1], 
        names.arg=c("Control", "Treated"), 
        cex.names=1 )

#this arrows function looks useful
#draw Control error bar first. 
arrows(data[1,2]-data[1,4], # says where to START the line across the bottom
       0.7,  # says where to start the line on the y co-ordinate
       data[1,2]+data[1,4],# says where to END the line across the bottom
       0.7, 
       angle=90, #draws a line instead of an arrow
       code=3, #draws lines at both ends
       length=0.25, #size of error bar
       lwd = 1.5)  #weight of line 

#draw Treated error bar second 
arrows(data[1,3]-data[1,5],
       1.9,
       data[1,3]+data[1,5],
       1.9, 
       angle=90, 
       code=3, 
       length=0.25,
       lwd = 1.5)


par(mfrow=c(3,1)) #layout three rows one column - so all on the same page

#Then turn it into a loop and create 3 plots...
for (i in 1:nrow(data)){
m<-c(data[i,3], data[i,2])
colors = c("red", "white")
sum = data[i,2] + data[i,3] + data[i,4] + data[i,5]
barplot(m, horiz=TRUE, 
        main = data[i,1], 
        names.arg=c("Treated", "Control"),
        las = 1,
        col=colors,
        cex.names=1,
        xlim = c(0, sum))

#draw the error bars
arrows(data[i,2]-data[i,4],
       1.9,
       data[i,2]+data[i,4],
       1.9, 
       angle=90,
       code=3, 
       length=0.1,
       lwd = 1.5) 


arrows(data[i,3]-data[i,5],
       0.7,
       data[i,3]+data[i,5],
       0.7, 
       angle=90, 
       code=3, 
       length=0.1,
       lwd = 1.5)
}

No comments:

Post a Comment