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 group
is 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, fill
is overwritten:
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)
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?
This is a bit of a hack, but you can reference
..x..
within thegeom_bar
call. The only problem is thatggplot
considers thisnumeric
and so I have coerced to factor and given nice labels within a call toscale_fill_brewer
compare with not coercing
..x..
to a factor