每个方面的总和百分比 - 尊重“填充” [英] Sum percentages for each facet - respect "fill"
问题描述
我正在尝试创建一个多面的barplot,每个方面的百分比总计为100。解决方案似乎是 group
和 .. density ..
的组合。在我看来, group
与 fill
冲突。
数据:
test< - data.frame(
pre>
test1 = sample(letters [1 :2],100,replace = TRUE),
test2 = sample(字母[3:8],100,replace = TRUE)
)
这会得到正确的百分比:
ggplot(test, aes(test2))+
geom_bar(aes(y = ..density ..,fill = test2,group = test1))+
facet_grid(〜test1)
$ c $你可以看到,fill
被覆盖:
然而,下面的代码尊重
fill
,但给了我错误的百分比(整个图表总和为100)(使用..density ..):
ggplot(test,aes(test2))+
geom_bar(aes(y = ..count ../ sum(.. count ..),fill = test2))+
facet_grid(〜tes t1)
是的 - 我可以创建额外的数据,但我觉得它属于表示层。其实这就像一个bug?
解决方案这有点破解,但你可以参考
..x ..
在geom_bar
调用中。唯一的问题是,ggplot
认为这个numeric
,所以我强迫要求在一次调用中给出好的标签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')
与不强制
.. x ..
的因子比较ggplot(test,aes(x = test2,group = test1))+
geom_bar(aes(y = ..density ..,fill = ..x ..))+
facet_grid (〜test1)
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 thatgroup
is conflicting withfill
.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
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 factorggplot(test, aes(x= test2, group = test1)) + geom_bar(aes(y = ..density.., fill = ..x..)) + facet_grid(~test1)
这篇关于每个方面的总和百分比 - 尊重“填充”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!