Friday, April 4, 2014

Create barplot in R

If you have a simple table e.g. expression values of two genes in different tissues and want to plot it as a barplot in R, do the following:

GENE1 GENE2
WhiteBloodCells 36 4
LymphNode 37 11
Brain 23 1
Heart 46 9
SkeletalMuscle 45 2
Colon 50 29
Adipocyte 36 7
Kidney 31 30
Liver 19 6
Lung 42 70
Thyroid 37 4
AdrenalGland 42 5
Breast 31 3
Ovary 49 40
Prostate 49 24
Testis 35 22

Save table as a text file e.g. gene1_gene2_expressiondata
In R use read.table

gene1_gene2 <- read.table("gene1_gene2_expressiondata", header=T, sep=" ")

Make a rotate function to inverse the table:

rotate <- function(x) t(apply(x, 2, rev))

Rotate the table:
gene1_gene2_rotate <- rotate(gene1_gene2)

Start a graphics device driver
x11()

Plot the graph. Use cex to regulate size of main, lab and axis, font=2 for bold font, col=rainbow(2) to pick two colors from the rainbow color palette.

barplot(as.matrix(gene1_gene2_rotate), beside=T, main="RNA-Seq data from human tissues - Illumina Human BodyMap 2.0", ylab="FPKMx100", xlab="Tissue", col=rainbow(2), cex.main=2, font.main=2, cex.lab=1.2, font.lab=2, cex.axis=1.2)


Use res, width and height to adjust the size of the graph and resolution you want.
dev.copy(jpeg,filename="gene1_gene2_plot.jpg", res=120, units="in", width=22, height=8)


Make a legend with rownames of gene1_gene2_rotate matrix, bty="o" to draw box or bty="n" without box

legend("topleft", rownames(gene1_gene2_rotate), cex=1.5, bty="n", fill=rainbow(2), text.font=2);
dev.off()

The output look like this:


No comments:

Post a Comment