I am trying to make a better version of an R base plot with ggplot2. Not only to have a common legend but also because I like the ggplot2 styles and customization. My data consists of 3 seperate datasets that contain the same two groups of observations for several (but different) treatments. Hence I want to generate 3 separate plots in 1 graph with a common legend however with different factor levels. To illustrate my point the first image here is what I have generated with R base so far:
I tried to generate a ggplot2 plot with dummy data that has exactly the same structure as my data:
foo<-data.frame(c(letters,letters),c(rep('T1',26),rep('T2',26)),
runif(52),rep(c(rep('Ori1',12),rep('Ori2',8),rep('ori3',6)),2))
names(foo)<-c('Treatment','Type','Count','Origin')
a<-ggplot(foo,aes(x = factor(Treatment),y = Count))
a+ facet_grid(Origin~., scales="free_y", space="free") +
geom_bar(stat="identity",aes(fill=factor(foo$Type)),position="dodge")
+theme_bw()+theme(axis.text.x=element_text(angle=60,hjust=1))+coord_flip()
Which gives me the following undesirable result.
I am aware of the stack overflow topics Removing Unused Factors from a Facet in ggplot2 and How can I remove empty factors from ggplot2 facets? however, they do not deal with the clustered bar graphs I try to realise here and I feel they are the problem, however do not now how to solve it. All pointers are welcome.
To illustrate my comment:
a<-ggplot(foo,aes(x = factor(Treatment),y = Count))
a+ facet_wrap(~Origin, scales="free_x") +
geom_bar(stat="identity",aes(fill=factor(Type)),position="dodge") +
theme_bw() +
theme(axis.text.x=element_text(angle=60,hjust=1))
Note that if you add coord_flip
and switch to free_y
you get a specific error about coord_flip
not working with some types of free scales, which is the source of you problem.
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