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%的比例显示完整条形。
有人可以帮忙吗?
答案 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))
答案 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)