George
George

Reputation: 903

Multiple series barplot

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.

Upvotes: 5

Views: 5917

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

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

Upvotes: 2

ConfusedMan
ConfusedMan

Reputation: 582

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

Upvotes: 4

Related Questions