【问题标题】:Percentage stacked barplot百分比堆积条形图
【发布时间】:2020-01-09 15:57:01
【问题描述】:

我想绘制一个带有质量百分比的堆积条形图,以量化每种尺寸对我拥有的优质衣服百分比的贡献。如果产品质量、尺寸和品牌仍然良好,我的表格显示 type = 1:

sok <- structure(list(type = c(0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0
), size = c("four", "four", "two", "three", "two", "two", "two", 
"three", "three", "four", "two", "two", "two"), brand = c("Armani", 
"Armani", "Armani", "Armani", "Armani", "Armani", "Armani", "Armani", 
"Armani", "Armani", "Armani", "Armani", "Armani")), row.names = c(NA, 
-13L), class = "data.frame")

我做的是:

sok %>%
    group_by(brand,size) %>%
    summarise(size_per_brand = n(),
              quality = as.numeric(mean(`type`) * 100))%>%
    ggplot(mapping = aes(x=brand, y = quality, fill = size)) +
    geom_col()

有这个:

这不是我想要的,因为我不想对百分比求和,但我想绘制我的优质 Armani 衣服的百分比 (46%),用尺寸填充它。我不是在寻找position = position_fill(),因为它会以 100% 显示完整的条形图。

有人可以帮忙吗?

【问题讨论】:

  • 可以包含多个品牌吗?它可能有助于了解您的复杂性。如果您没有多个品牌,则无需按品牌分组。
  • 是的,复杂性在于我与多个品牌合作,但我避免将它们包括在内,以便提出最简单的问题。
  • 如果您不想对它们求和,您希望堆叠如何工作?我不清楚这里想要的结果是什么。
  • 我想在吧台上展示 46% 的优质衣服。堆叠应按尺寸显示优质衣服的百分比。一种低于46%的百分比

标签: r


【解决方案1】:

这是你要找的吗?

library(tidyverse)
library(scales)

sok %>%
  group_by(brand,size) %>%
  summarise(size_per_brand = n(),
            quality = mean(type)) %>%
  group_by(brand) %>% 
  mutate(perc = quality / sum(quality)) %>% 
  ggplot(aes(x = brand, y = perc, fill = size)) +
  geom_col() +
  geom_text(aes(label = if_else(perc > 0, percent(perc, accuracy = 1), NA_character_)), position = position_stack(vjust = 0.5)) +
  scale_y_continuous(labels = function(x) percent(x, accuracy = 1))

【讨论】:

    【解决方案2】:

    您可以使用prop.table()

    armani <- with(sok, prop.table(table(type, size)))
    #     size
    # type       four      three        two
    #    0 0.07692308 0.23076923 0.23076923
    #    1 0.15384615 0.00000000 0.30769231
    

    既然你只想要"type == 1",那么创建一个子集并定义它as.matrix

    armani.1 <- as.matrix(armani[rownames(armani) == 1, ])
    

    定义颜色,在本例中为三种。

    clr <- rainbow(nrow(armani.1), alpha=.7)
    

    现在您可以使用barplot、自定义坐标轴并添加图例。

    barplot(armani.1, ylim=c(0, 1), yaxt="n", col=clr,
            main="Good quality clothes by size")
    axis(2, (0:10)/10, labels=FALSE)
    mtext(paste0((0:5)*20, "%"), 2, 1, at=(0:5)*.2, las=2)
    mtext("Armani", 1, 1, font=2)
    legend("topright", rownames(Armani), title="Size", cex=.8, 
           pch=15, col=clr)
    

    产量

    【讨论】:

    • 谢谢!但我只对 prop.table(table(brand, type) 的 x = 1 感兴趣。我想准确地显示该栏对应于大小的子栏(百分比)。抱歉造成混淆