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.
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)   
With Tyler's suggested change: + theme(panel.margin = grid::unit(-1.25, "lines"))

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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With