【问题标题】:Showing percentage in bars in ggplot在ggplot中以条形显示百分比
【发布时间】:2023-04-02 17:52:01
【问题描述】:

我有一个包含二进制变量的数据集,如下所示。

M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5)
M4 <- as.data.frame(M4)
M4$id <- 1:20

我使用下面的代码制作了一个堆积条形图

library(reshape)
library(ggplot2)
library(scales)
M5 <- melt(M4, id="id")
M5$value <- as.factor(M5$value)
ggplot(M5, aes(x = variable)) + geom_bar(aes(fill = value), position = 'fill') +
  scale_y_continuous(labels = percent_format())

现在我希望在图表中显示每个条形中每个字段的百分比,以便每个条形达到 100%。我试过123 和几个类似的问题,但我找不到任何适合我情况的例子。如何管理此任务?

【问题讨论】:

    标签: r graphics ggplot2 bar-chart percentage


    【解决方案1】:

    试试这个方法:

    test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
      geom_bar() +
      scale_y_continuous(labels = percent_format()) +
      stat_bin(aes(label=paste("n = ",..count..)), vjust=1, geom="text")
    test
    

    已编辑:给出百分比并使用 scales 包:

    require(scales)
    test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
      geom_bar() +
      scale_y_continuous(labels = percent_format()) +
      stat_bin(aes(label = paste("n = ", scales::percent((..count..)/sum(..count..)))), vjust=1, geom="text")
    test
    

    【讨论】:

    • 在我看来这不是百分比,您可能想要paste(round((..count..)/sum(..count..)*100), "%")(而不是paste("n = ",..count..))之类的东西
    • 非常感谢您的帮助!计算得很好,但我正在寻找百分比;也许您可以就此提供一些建议?将不胜感激。
    • @Arenburg:该代码返回整个图表的累积百分比,而不是每个条形图。换句话说,所有条中的所有字段加起来是 100%,而我需要每个条加起来是 100%。
    【解决方案2】:

    您可以使用sjPlot-package 中的sjp.stackfrq 函数(请参阅examples here)。

    M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5)
    M4 <- as.data.frame(M4)
    sjp.stackfrq(M4)
    # alternative colors: sjp.stackfrq(M4, barColor = c("aquamarine4", "brown3"))
    

    可以使用各种参数自定义绘图外观...

    【讨论】:

      【解决方案3】:

      我真的很喜欢 ggplot 本身创建的隐式信息的使用,如本文所述:

      using the ggplot_build() function

      在我看来,这为最终控制 ggplot 图表的外观提供了很多机会。

      希望这能有所帮助

      汤姆

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-05
        • 1970-01-01
        • 2020-12-04
        • 1970-01-01
        • 2022-11-15
        • 1970-01-01
        相关资源
        最近更新 更多