我正在绘制一个分类变量,而不是显示每个类别值的计数.
我正在寻找一种方法来ggplot显示该类别中的值的百分比.当然,有可能用计算的百分比创建另一个变量并绘制一个变量,但我必须做几十次,我希望在一个命令中实现它.
我正在尝试类似的东西
qplot(mydataf) +
  stat_bin(aes(n = nrow(mydataf), y = ..count../n)) +
  scale_y_continuous(formatter = "percent")
但我必须错误地使用它,因为我有错误.
为了轻松重现设置,这里有一个简化的例子:
mydata <- c ("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc");
mydataf <- factor(mydata);
qplot (mydataf); #this shows the count, I'm looking to see % displayed.
在实际情况中,我可能会使用ggplot而不是qplot,但使用stat_bin的正确方法仍然无法使用.
我也试过这四种方法:
ggplot(mydataf, aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(formatter = 'percent');
ggplot(mydataf, aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(formatter = 'percent') + geom_bar();
ggplot(mydataf, aes(x = levels(mydataf), y = …我想要一个这样的情节,除了每个方面总和达到100%.现在组M是0.05 + 0.25 = 0.30而不是0.20 + 0.80 = 1.00.
df <- rbind(
    data.frame(gender=c(rep('M',5)), outcome=c(rep('1',4),'0')),
    data.frame(gender=c(rep('F',10)), outcome=c(rep('1',7),rep('0',3)))
)
df
ggplot(df, aes(outcome)) +
    geom_bar(aes(y = (..count..)/sum(..count..))) +
    facet_wrap(~gender, nrow=2, ncol=1) 
(使用y = ..density ..会产生更糟糕的结果.)
我想用facet_wrap绘制一个ggplot,它不会显示实际的表百分比,而是显示每组中给定答案的百分比.我必须这样做,因为我想表明,哪个答案选择最多,每个组最重要.这些组的大小不同.
示例数据:
group <- c(rep(c("Group1"), times = 10),rep(c("Group2"), times = 6),rep(c("Group3"), times = 4))
choice <- c(rep(c("a","b","c"),length.out = 10), "a","a","a","a","b","c","b","b","b","c")
df <- data.frame(cbind(group,choice))
如果我不能使用整体prop.t,那将是很好的,但prop.c要在我的情节中显示,因为显示重要,例如,第2组的66.67%更喜欢选择a.
library(gmodels)
CrossTable(choice, group, prop.chisq=FALSE, prop.t = TRUE, prop.c = TRUE, prop.r = FALSE, format = "SPSS")
这是为了情节:
library(ggplot2)
g <- ggplot(df, aes_string(x="group", fill="group")) +
            geom_bar(aes(y = (..count..)/sum(..count..)))+
            ylab("percent")
g + facet_wrap(~ choice)

现在第一个酒吧节目:20%,20%,0%,但应该显示40%,66.67%和0%(组中每个人的百分比,谁给出了这个答案).
对于第二个栏应显示:30%,16.667%和75%.
第三栏:30%,16.667%和25%
谢谢您的帮助.