I thought stacking columns was the default action under ggplot2 but that does not seem to be happening for my plot. I am trying to take two vectors (may or may not have the same length) and graph them in the same plot as stacked bars. Here is a simple example:
z1<-c(500, 300, 200, 100)
z2<-c(800, 100, 50)
names(z1)<-c("a", "b", "c", "d")
names(z2)<-c("a", "c", "e")
z1<-as.data.frame(z1)
z2<-as.data.frame(z2)
colnames(z1)<-"total"
colnames(z2)<-"total"
ggplot()+
labs(x="", y="") +
theme_bw() + theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) +
scale_y_continuous(labels=format_si()) +
ggtitle("Test") +
geom_bar(data=z1, aes(x=rownames(z1), y=total),position="identity",stat="identity",
fill=rgb(red=200, green=0, blue=50, maxColorValue = 255)) +
geom_bar(data=z2, aes(x=rownames(z2), y=total),position="identity",stat="identity",
fill=rgb(red=0, green=200, blue=50, maxColorValue = 255))
Gives me:
As you can see, the a and c elements are in front of each other instead of stacked.


geom_barcall will be stacked. Differentgeom_barcalls don't stack with each other. If you tidy your data, everything will work as you expect.tidyr::gatherorreshape2::meltto get your data in long format (lots of examples on Stack Overflow if you search for "wide to long data"), add a column indicating color, and thenrbindthe two data frames together.df <- merge(z1, z2, by = "row.names", all=T);df <- reshape(df, dir = "long", varying = 2:3);ggplot(df, aes(x=Row.names, y=total, fill=time)) + geom_bar(stat="identity".