我想用facelet来使用geo_bar
,获得的百分比而不是绝对计数,但百分比应该是相对于每个方面,而不是相对于整体计数。ggplot2:geom_bar,计算方面的百分比
这已经讨论了很多(example),建议使用geom_bar(aes(y = (..count..)/sum(..count..)))
。这不适用于facet(即会给出总计数)。有人提出了更好的解决方案, 改为使用。
这似乎是工作,如果x
是数字,但如果x
是字符:所有的酒吧都在100%!为什么?难道我做错了什么?谢谢!
library(tidyverse)
df <- data_frame(val_num = c(rep(1, 60), rep(2, 40), rep(1, 30), rep(2, 70)),
val_cat = ifelse(val_num==1, "cat", "mouse"),
group=rep(c("A", "B"), each=100))
#works with numeric
ggplot(df) + stat_count(mapping = aes(x=val_num, y=..prop..)) + facet_grid(group~.)
# does not work?
ggplot(df) + stat_count(mapping = aes(x=val_cat, y=..prop..)) + facet_grid(group~.)
如果您的x轴是类别,您基本上会问“哪些猫是猫的百分比以及哪个百分比的小鼠是老鼠?” – lebelinoz
我认为这个问题是在小组/面A内,猫(或值1)与小鼠(值2)的比例是多少。对于B组也一样,不是吗?但是,是的,也许我的问题是不适当的?我仍然不明白为什么数字而不是字符的行为是不同的? – Matifou