Thursday, April 29, 2010

R plotting

How to make a simple plot

table <- read.table(file="filename", header=TRUE)
plot(table$col1name, table$col2name, xlim=c(0,max_x_val), ylim=c(0,max_y_val), xlab = "X-axis Label", ylab="Y-axis Label", main = "Main Plot Lable", type = "b", pch = 21)
points(table$col1name, table$col3name)
hist(table$col1name, breaks = numofbreaks)
mtext(side, line, "Text to add to my graph on a certain side and line")
roundednumber <- format(number, digits=2)
mtext(side, line+1, roundednumber)
  • Having table a header line makes life easier
  • if you don't have a header then use V1 for col1name and V2 for col2name
  • type b is line and character and 21 is an open circle, there are point characters (pch) from 1-25.
  • for a histrogram use hist
  • for plotting multiple datasets use points

To export your plot to a file

postscript(file="name", paper="letter", horizontal=FALSE)
par(mfrow=c(1,2))
attach(table) 
plot(col1name, col2name, xlim=c(0,max_x_val), ylim=c(0,max_y_val), xlab = "X-axis Label", ylab="Y-axis Label", main = "Main Plot Lable", type = "b", pch = 21)
hist(col1name, breaks = numofbreaks)
mtext(side, line, "Text to add to my graph on a certain side and line")
roundednumber <- format(number, digits=2)
mtext(side, line+1, roundednumber)
dev.off()

Using Linear Regression

linearmodel <- lm(table$col2name ~ table$col1name)
plot(table$col1name, table$col2name, xlim=c(0,max_x_val), ylim=c(0,max_y_val), xlab = "X-axis Label", ylab="Y-axis Label", main = "Main Plot Lable", type = "b", pch = 21)
abline(linearmodel)
rsquared <- summary(linearmodel)$r.squared
intercept <- summary(linearmodel)$coef[1,1]
slope <- summary(linearmodel)$coef[2,1]

How to create a function with color in R

  • Note that functions can be made with things other than color, such as point character.
evalue.colors <- function(n) {
 colorvec <- vector(mode="character", length=length(n))
 for (i in 1:length(n)) {
  colorvec[i] = "light grey"
  if ( n[i] <= 1e-03 ) {
   colorvec[i] = "orange"
  }
  if (n[i] <= 1e-06 ) {
   colorvec[i] = "red"
  }
  if( n[i] <= 1e-09) {
   colorvec[i] = "purple"
  }
  if( n[i] <= 1e-12) {
   colorvec[i] = "blue"
  }
 }
 c(colorvec)
}

plot(x,y, col = evalue.colors(vector or matrix column containing evalues))

No comments:

Post a Comment