Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty factors from clustered bargraph in ggplot2 with multiple facets

Tags:

r

ggplot2

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: r base plot closest plot realisation

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. failed ggplot2 image

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.

like image 370
FM Kerckhof Avatar asked Apr 08 '13 19:04

FM Kerckhof


1 Answers

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))

enter image description here

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.

like image 162
joran Avatar answered Nov 03 '22 01:11

joran