我想使用geo_barwith facets,获得百分比而不是绝对计数,但百分比应该相对于每个方面,而不是相对于整体计数。
这已经讨论了很多(示例),建议使用geom_bar(aes(y = (..count..)/sum(..count..))). 这不适用于方面(即会给出总数)。已经提出了更好的解决方案,stat_count(mapping = aes(x=x_val, y=..prop..))改为使用。
如果x是numeric,这似乎有效,但如果x是character 则无效:所有条形都是 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~.)
Run Code Online (Sandbox Code Playgroud)