Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay bar graphs in ggplot2 [duplicate]

Tags:

r

ggplot2

I'm trying to overlay bar graphs in ggplot2

My current code produces a bar plot but they are stacked on top of each other. I dont want this, I would like them overlaid so I can see the differences in each bar height.

Code:

library(ggplot2)
library(reshape)


x = c("Band 1", "Band 2", "Band 3")
y1 = c("1","2","3")
y2 = c("2","3","4")

to_plot <- data.frame(x=x,y1=y1,y2=y2)
melted<-melt(to_plot, id="x")

print(ggplot(melted,aes(x=x,y=value,fill=variable)) + geom_bar(stat="identity", alpha=.3))

Stacked output:

enter image description here

like image 943
Harpal Avatar asked Oct 23 '12 16:10

Harpal


1 Answers

Try adding position = "identity" to your geom_bar call. You'll note from ?geom_bar that the default position is stack which is the behavior you're seeing here.

When I do that, I get:

print(ggplot(melted,aes(x=x,y=value,fill=variable)) + 
        geom_bar(stat="identity",position = "identity", alpha=.3))

enter image description here

And, as noted below, probably position = "dodge" would be a nicer alternative:

enter image description here

like image 91
joran Avatar answered Oct 18 '22 14:10

joran