英文:
add values to a stacked barplot
问题
可以有人帮我将百分比添加到以下的条形图中吗?
library(ggplot2)
library(dplyr)
n <- 10000
test <- data.frame(value = sample(1:3, size = n, replace = TRUE),
grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) %>%
mutate(value = as.factor(value))
test %>%
ggplot(aes(x = grp, fill = value, group = value)) +
geom_bar(position = 'fill') +
facet_wrap(item ~., ncol = 2) +
coord_flip() +
scale_fill_manual(values = c("green", "yellow", "red"))
英文:
Can someone please help me with adding percentages to the following barplot?
library(ggplot2)
library(dplyr)
n <- 10000
test <- data.frame(value = sample(1:3, size = n, replace = TRUE),
grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) %>%
mutate(value = as.factor(value))
test %>%
ggplot(aes(x = grp, fill = value, group = value)) +
geom_bar(position = 'fill') +
facet_wrap(item ~., ncol = 2) +
coord_flip() +
scale_fill_manual(values = c("green", "yellow", "red"))
答案1
得分: 1
以下是您要翻译的内容:
"The linked answer is similar but only viable for 2 groups. Following the rabbit hole here is a solution for more than 2 from https://rstudio-pubs-static.s3.amazonaws.com/329677_8f579b9e46284caeb9d3a72b7fdb7ac3.html"
"Code from linked site."
英文:
The linked answer is similar but only viable for 2 groups. Following the rabbit hole here is a solution for more than 2 from https://rstudio-pubs-static.s3.amazonaws.com/329677_8f579b9e46284caeb9d3a72b7fdb7ac3.html
test %>%
ggplot(aes(x = grp, fill = value, group = value)) +
geom_bar(position = 'fill') +
facet_wrap(item ~., ncol = 2) +
coord_flip() +
scale_fill_manual(values = c("green", "yellow", "red")) +
geom_text(aes(label=scales::percent(after_stat(count)/sum(after_stat(count)))),
stat='count',position=position_fill(vjust=0.5))
Update per comment to add to 100:
# create new data
percentData <- test %>% group_by(grp) %>% count(value) %>%
mutate(ratio=scales::percent(n/sum(n)))
percentData
test %>%
ggplot(aes(x = grp, fill = value, group = value)) +
geom_bar(position = 'fill') +
facet_wrap(item ~., ncol = 2) +
coord_flip() +
scale_fill_manual(values = c("green", "yellow", "red")) +
geom_text(data=percentData, aes(y=n,label=ratio),
position=position_fill(vjust=0.5))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论