堆积条形图百分比

时间:2020-01-09 15:57:01

标签: r

我想用质量百分比绘制堆积条形图,以便量化每种尺寸对我所拥有的优质衣服百分比的贡献。如果产品仍然具有良好的质量,尺寸和品牌,则我的表格显示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()

具有: enter image description here

这不是我想要的,因为我不想对百分比求和,但我想绘制出我的优质Armani衣服的百分比(46%),并按尺寸填充。我不需要position = position_fill(),因为它将以100%的比例显示完整条形。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

这是您要找的吗?

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))

enter image description here

答案 1 :(得分:0)

您可以使用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)

产量

enter image description here