每个方面的总和百分比 - 尊重“填充” [英] Sum percentages for each facet - respect "fill"

查看:133
本文介绍了每个方面的总和百分比 - 尊重“填充”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个多面的barplot,每个方面的百分比总计为100。解决方案似乎是 group .. density .. 的组合。在我看来, group fill 冲突。



数据:

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

pre>

这会得到正确的百分比:

  ggplot(test, aes(test2))+ 
geom_bar(aes(y = ..density ..,fill = test2,group = test1))+
facet_grid(〜test1)
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 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:

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)

这篇关于每个方面的总和百分比 - 尊重“填充”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆