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