14

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?

Community
  • 1
  • 1
Andreas
  • 6,612
  • 14
  • 59
  • 69

1 Answers1

14

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

mnel
  • 113,303
  • 27
  • 265
  • 254
  • I love that Set3 pallete! – duhaime Mar 08 '15 at 16:49
  • @mnel, I was trying to generate a similar bar plot in Shiny with position = "dodge", however getting all bars 100%. It would be great if you could suggest where I am going wrong. Thank you and sorry for getting in touch in this way. I have posted the question at http://stackoverflow.com/questions/41078480/r-shiny-ggplot-bar-and-line-charts-with-dynamic-variable-selection-and-y-axis-to – user1412 Dec 11 '16 at 07:46