简体   繁体   English

百分比堆积条形图

[英]Percentage stacked barplot

i want to plot a stacked barplot with quality percentage in order to quantify the contribute of each size for the percentage of quality clothes i have.我想绘制一个带有质量百分比的堆叠条形图,以便量化每种尺寸对我拥有的质量百分比的贡献。 here my table displaying type = 1 if the product was still in good quality, size and brand:如果产品的质量、尺寸和品牌仍然良好,我的表格显示类型 = 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")

What i do is:我做的是:

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

having this:有这个: 在此处输入图片说明

which is not what i want because i dont want to sum the percentages but i want to plot the percentage (46%) of my good quality Armani clothes filling it with the contribute by size.这不是我想要的,因为我不想对百分比求和,但我想绘制我的优质阿玛尼服装的百分比 (46%),并用尺寸贡献填充它。 I am not looking for position = position_fill() as it will display the full bar at 100%.我不是在寻找position = position_fill()因为它会以 100% 的比例显示完整的条形图。

Can somebody help?有人可以帮忙吗?

Is this what you're looking for?这是你要找的吗?

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

在此处输入图片说明

You can use prop.table() .您可以使用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

Since you just want "type == 1" , make a subset and define it as.matrix .由于您只想要"type == 1" ,请创建一个子集并将其定义为as.matrix

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

Define colors, three in this case.定义颜色,在本例中为三种。

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

Now you could use barplot , customize axes, and add a legend.现在您可以使用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)

Yields产量

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM