我正在尝试创建一个使用边缘(行)比例而不是单元格比例的分组条形图,并且无法弄清楚如何更改:
y = (..count..)/sum(..count..)
在ggplot中执行此操作。
使用mtcars数据集作为示例并考虑两个分类变量(cyl和am - 纯粹为了示例而将cyl作为响应而作为解释变量)。任何人都可以帮我这样做:
data(mtcars)
# Get Proportions
mtcars_xtab <- table(mtcars$cyl,mtcars$am)
mtcars_xtab
margin.table(mtcars_xtab, 1) # A frequencies (summed over B)
margin.table(mtcars_xtab, 2) # B frequencies (summed over A)
prop.table(mtcars_xtab) # cell percentages - THIS IS WHAT'S USED IN THE PLOT
prop.table(mtcars_xtab, 1) # row percentages - THESE ARE WHAT I WANT TO USE IN THE PLOT
# Make Plot
mtcars$cyl <- as.factor(mtcars$cyl)
mtcars$am <- as.factor(mtcars$am)
ggplot(mtcars, aes(x=am, fill=cyl)) +
geom_bar(aes(y = (..count..)/sum(..count..)), position = "dodge") +
scale_fill_brewer(palette="Set2")
谢谢。