代码之家  ›  专栏  ›  技术社区  ›  Marco

ggplot:如何在柱状图的支柱顶部添加一定百分比

  •  2
  • Marco  · 技术社区  · 7 年前

    我需要复制直方图/条形图的特定格式。我已经对 ggplot 为了对分类x变量进行分组,并用十六进制指定颜色。

    以下是我尝试绘制/复制的内容:

    enter image description here

    以下是我的数据结构的MWE:

    sex <- sample(0:1, 100, replace=TRUE)
    group <- sample(2:5, 100, replace=TRUE)
    data <- data.frame(sex, group)
    
    library(ggplot2)
    ggplot(data, aes(x = group, group=sex, fill=factor(sex) )) +
      geom_histogram(position="dodge", binwidth=0.45) +                      
      theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +    
      guides(fill=guide_legend(title="sex")) +                        
      scale_y_continuous(labels = scales::percent_format())   +              
      scale_fill_manual(values=c("#b6181f", "#f6b8bb")) 
    

    我得到:

    enter image description here

    我无法处理的小事包括:

    • 替换x轴上的因子标签,我的直方图方法可能有问题,但我也没有找到使用条形图的实用方法
    • 百分数四舍五入,百分数无小数

    但最重要的是,我不知道如何在每个栏的顶部为一组、一个性别添加一个百分比值。。

    我期待着一些建议:)

    1 回复  |  直到 4 年前
        1
  •  3
  •   Axeman    7 年前

    首先,我会将x轴数据视为因子,并将其绘制为条形图。将百分比值文本置于条形图顶部查看此问题: Show % instead of counts in charts of categorical variables . 此外,y轴百分比值不是舍入的问题,它们实际上不是百分比值。 y = ..prop.. 解决了这个问题。

    你在找那个吗(我总结了一切)?

    sex <- sample(0:1, 100, replace=TRUE)
    group <- sample(2:5, 100, replace=TRUE)
    data <- data.frame(sex, group)
    
    labs <- c("Score < 7", "Score\n7 bis < 12", "Score\n12 bis < 15",
              "Score\n15 bis < 20","Score >= 20")
    
    ggplot(data, aes(x = as.factor(group), y = ..prop.., group = sex, fill = factor(sex) )) +
      geom_bar(position = "dodge") +
      geom_text(aes(label = scales::percent(..prop..)), 
                position = position_dodge(width = 0.9), stat = "count", vjust = 2) +
      labs(x = NULL, y = NULL) +
      guides(fill = guide_legend(title = "sex")) +                        
      scale_y_continuous(labels = scales::percent_format())   +              
      scale_fill_manual(values=c("#b6181f", "#f6b8bb")) +
      scale_x_discrete(labels = labs)
    

    enter image description here