首页 > 解决方案 > 在条形图中为分类变量添加计数百分比;ggplots

问题描述

我需要有人帮我编辑我的代码以添加计数百分比作为列标签

我有代码

scandals_deal_breaker <- data[, c("Q19.A: Sexual harassment",
                                  "Q19.B: Racism",                                                                                                                                       
                                  "Q19.C: Violence",                                                                                                                                     
                                  "Q19.D: Fraud and money laundering",                                                                                                                   
                                  "Q19.E: Alcohol and drug use")]


scandals_deal_breaker_count1 <- ldply(scandals_deal_breaker,
                                      function(c) sum(c=="1")/52) 

ggplot(scandals_deal_breaker_count1, aes(x=reorder(.id, -V1), y=V1)) + 
  geom_bar(stat="identity") + 
  xlab("") + ylab("") + 
  scale_x_discrete(breaks = c("Q19.A: Sexual harassment",
                              "Q19.B: Racism",                                                                                                                                       
                              "Q19.C: Violence",                                                                                                                                     
                              "Q19.D: Fraud and money laundering",                                                                                                                   
                              "Q19.E: Alcohol and drug use"),
                   labels = str_wrap(c("Sexual harassment","Racism","Violence",
                                       "Fraud and money laundering",
                                       "Alcohol and drug use"), width = 14)) +
  scale_y_continuous(labels = percent) +
  ggtitle("What types of scandals are \"deal-breakers\" for you?") +
  theme(plot.title = element_text(hjust = 0.5 , size = 8.5))

这是一道选择题,百分比的总和应超过 100%。我希望添加每列的百分比。

我尝试添加以下代码,但它为每个选项添加了 20% 的标签

geom_text(
    stat='count', 
    aes(y=after_stat(..count..),
        label=after_stat(scales::percent(..count../sum(..count..),1))),
    position=position_fill(0.5),
  )

图表

标签: rggplot2bar-chartcategorical-data

解决方案


推荐阅读