Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple series barplot

Tags:

r

ggplot2

I have matrix the looks like this (expect with four numeric variables)

GeneId<- c("x","y","z")
Var1<- c(0,1,3)
Var2<- c(1,2,1)

df<-cbind(GeneId, Var1,Var2)

What I what to plot is a bar graph where each gene has a bar for each variable grouped (i.e x would have bar1 = height 0, bar2 = 1) I can do individual graphs by writing a loop and plotting each row:

for (i in 1:legnth(df$GeneId){
  barplot(as.numeric(df[i,]), main= rownames(df)[i])
}

But I would like to have the plots on the same graph. Any ideas? I thought of doing using either ggplot2 or lattice but from what I have seen they are only able to put them in a grid together, axis are independent of each other.

like image 423
George Avatar asked Mar 18 '15 20:03

George


2 Answers

The simplest answer would be to use

barplot(rbind(Var1,Var2),col=c("darkblue","red"),beside = TRUE)

I recommend you to read and experiment using barplot

like image 189
ConfusedMan Avatar answered Nov 19 '22 05:11

ConfusedMan


Try this:

df=data.frame(GeneId=c("x","y","z"), Var1=c(0,1,3),Var2=c(1,2,1))

library(reshape2)
library(ggplot2)

df_ = melt(df, id.vars=c("GeneId"))
ggplot(df_, aes(GeneId, value, fill=variable)) +
geom_bar(stat='Identity',position=position_dodge())

enter image description here

like image 33
Colonel Beauvel Avatar answered Nov 19 '22 06:11

Colonel Beauvel