Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - bar plot with both stack and dodge

Tags:

r

ggplot2

I am trying to create a barplot using ggplot2 where I am stacking by one variable and dodging by another.

Here is an example data set:

df=data.frame(   year=rep(c("2010","2011"),each=4),   treatment=rep(c("Impact","Control")),   type=rep(c("Phylum1","Phylum2"),each=2),   total=sample(1:100,8)) 

I would like to create a barplot where x=treatment, y=total, the stacked variable is type and the dodged variable is year. Of course I can do one or the other:

ggplot(df,aes(y=total,x=treatment,fill=type))+geom_bar(position="dodge",stat="identity")  ggplot(df,aes(y=total,x=treatment,fill=year))+geom_bar(position="dodge",stat="identity") 

But not both! Thanks to anyone who can provide advice.

like image 770
jslefche Avatar asked Oct 03 '12 19:10

jslefche


2 Answers

Here's an alternative take using faceting instead of dodging:

ggplot(df, aes(x = year, y = total, fill = type)) +     geom_bar(position = "stack", stat = "identity") +     facet_wrap( ~ treatment) 

enter image description here

With Tyler's suggested change: + theme(panel.margin = grid::unit(-1.25, "lines"))

enter image description here

like image 188
Matt Parker Avatar answered Sep 21 '22 23:09

Matt Parker


You can use interaction(year, treatment) as the x-axis variable as an alternative to dodge.

library(dplyr) library(ggplot2)   df=data.frame(   year=rep(c("2010","2011"),each=4),   treatment=rep(c("Impact","Control")),   type=rep(c("Phylum1","Phylum2"),each=2),   total=sample(1:100,8)) %>%    mutate(x_label = factor(str_replace(interaction(year, treatment), '\\.', ' / '),                           ordered=TRUE))  ggplot(df, aes(x=x_label, y=total, fill=type)) +   geom_bar(stat='identity') +   labs(x='Year / Treatment') 

Created on 2018-04-26 by the reprex package (v0.2.0).

like image 36
Kent Johnson Avatar answered Sep 23 '22 23:09

Kent Johnson