【问题标题】:Calculate percentage value of grouped value in geom_bar while showing count per grouped value计算 geom_bar 中分组值的百分比值,同时显示每个分组值的计数
【发布时间】:2020-09-12 21:18:14
【问题描述】:

我正在尝试使用 ggplot2 在堆积栏中显示计数和百分比数据。数据在这里

https://github.com/oiramsch/CvsRWO/blob/master/colorList.csv

我试过了:

p <- colorList %>% ggplot(mapping = aes(x=factor(age, levels = c("young","old")),fill=factor(answer_correct, levels = c(0,1), labels = c("False","Correct"))))

然后

p + geom_bar(stat="count", position="stack")+facet_grid(~condition)+labs(title="Colors",subtitle = "per setsize grouped by age", x="", y="Count answer correct", fill="Answer correct")+geom_text(aes(label = paste(..count..,"\n",scales::percent(..count../1298,0.01))),position=position_stack(0.5),stat="count")

结果我收到了:

问题是我使用固定值 1298 作为总值来计算百分比份额(不幸的是,并非所有列都如此)。所以我正在寻找一个 ggplot 的内部变量,我可以使用它来访问每列的总和,甚至更好地访问每个集合大小的错误/正确值的百分比。但我无法弄清楚如何做到这一点。当然,我可以提前总结数据,但我认为 ggplot 内部必须有一个解决方案......如果有人知道如何修复我的代码,我将不胜感激。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我建议采用这种方法总结价值,这可能是您的一个选择:

    library(ggplot2)
    library(dplyr)
    #Data
    colorList <- read.csv('https://raw.githubusercontent.com/oiramsch/CvsRWO/master/colorList.csv',stringsAsFactors = F)
    #Aggregate
    colorList %>% mutate(age=factor(age, levels = c("young","old")),
                 answer_correct=factor(answer_correct, levels = c(0,1))) %>%
      group_by(age,condition,answer_correct) %>% summarise(N=n()) %>% ungroup() %>%
      group_by(age,condition) %>% 
      mutate(Total=sum(N),Percent=N/Total,
             Lab=paste0(N,' (',paste0(round(100*Percent,0),'%'),')')) -> Sums
    #Plot
    ggplot(Sums,aes(x=age,y=N,fill=answer_correct))+
      geom_bar(stat='identity',position = position_stack())+
      facet_wrap(.~condition,scales = 'free')+
      geom_text(aes(label=Lab),position = position_stack(vjust = .5),size=3)+
      geom_text(aes(y=Total,label=Total),vjust=-0.25,size=3)
    

    输出:

    【讨论】:

    • thx 鸭子,也许你是对的,在绘制数据之前聚合数据,比在 ggplot 中寻找内部解决方案更容易。这是务实和快速的。我认为 ggplot 可以自己做,但可能是我错了。谢谢你的代码。
    • @Oiramsch 是的,对数据进行编码更优化,这样您就可以为您的绘图获得完美的输入,如您所见。我希望这对您有用,如果您认为这是一个有用的答案,您可以通过单击此答案左侧的勾号来接受它。这取决于你:)
    【解决方案2】:

    你在找(..count..)/sum(..count..)吗?

    p + 
      geom_bar(stat="count", position="stack")+
      facet_grid(~condition)+
      labs(title="Colors",subtitle = "per setsize grouped by age", x="", y="Count answer correct", fill="Answer correct")+
      geom_text(aes(label = paste(..count..,"\n",
                                  scales::percent(..count../sum(..count..), 0.01))),
                position=position_stack(0.5),stat="count")
    

    【讨论】:

    • 谢谢李曼,我试过了。但是sum(..count..) 正在返回所有正确答案的总数,所以大约是 10400。我正在寻找每列正确/错误答案的总数。我认为有一个内部变量 ..??.. 对每个柱进行总结。
    猜你喜欢
    • 2012-09-08
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多