Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum percentages for each facet - respect "fill"

Tags:

r

ggplot2

I am trying to create a faceted barplot, with percentages adding up to 100 for each facet. The solution to this seems to be a combination of group and ..density... How ever - it seems to me that groupis conflicting with fill.

Data:

test <- data.frame(
     test1 = sample(letters[1:2], 100, replace = TRUE), 
     test2 = sample(letters[3:8], 100, replace = TRUE)
 )

This gets the percentages right:

ggplot(test, aes(test2)) +
     geom_bar(aes(y = ..density.., fill=test2,group=test1)) + 
     facet_grid(~test1)

Bus as you can see, fillis overwritten: percentage sums to 100 for each facet

However, the code below respects fill but gives me the wrong percentages (sums to 100 for the whole chart)(using ..density..):

ggplot(test, aes(test2)) +
     geom_bar(aes(y = ..count../sum(..count..), fill=test2)) + 
     facet_grid(~test1)

percentage sums to 100 for the total chart

Related: This old question of mine: percentage on y lab in a faceted ggplot barchart?.

And yes - I could create additional data, but I feel this belongs in the presentation layer. Actually this feels like a bug?

like image 671
Andreas Avatar asked Sep 02 '12 13:09

Andreas


1 Answers

This is a bit of a hack, but you can reference ..x.. within the geom_bar call. The only problem is that ggplot considers this numeric and so I have coerced to factor and given nice labels within a call to scale_fill_brewer

ggplot(test, aes(x= test2, group = test1)) + 
   geom_bar(aes(y = ..density.., fill = factor(..x..))) + 
   facet_grid(~test1) + 
   scale_fill_brewer(name = 'test2', breaks = 1:6, 
                     labels = levels(test$test2), palette = 'Set3')

enter image description here

compare with not coercing ..x.. to a factor

ggplot(test, aes(x= test2, group = test1)) + 
  geom_bar(aes(y = ..density.., fill = ..x..)) +
   facet_grid(~test1)

enter image description here

like image 101
mnel Avatar answered Nov 04 '22 08:11

mnel