gpt4 book ai didi

r - 如何使用 facet_wrap 绘制 ggplot2,显示每个组的百分比,而不是整体百分比?

转载 作者:行者123 更新时间:2023-12-04 10:34:36 25 4
gpt4 key购买 nike

我想用 facet_wrap 绘制一个 ggplot,它不显示实际的表格百分比,而是每组中给定答案的百分比。我必须这样做,因为我想表明,对于每个组来说,哪个答案最受选择和最重要。组的大小不一样。

示例数据:

group <- c(rep(c("Group1"), times = 10),rep(c("Group2"), times = 6),rep(c("Group3"), times = 4))
choice <- c(rep(c("a","b","c"),length.out = 10), "a","a","a","a","b","c","b","b","b","c")
df <- data.frame(cbind(group,choice))

如果我不能使用整体 prop.t就好了,但是 prop.c在我的图中显示,因为显示很重要,例如,第 2 组的 66.67% 更喜欢选择 a。
library(gmodels)
CrossTable(choice, group, prop.chisq=FALSE, prop.t = TRUE, prop.c = TRUE, prop.r = FALSE, format = "SPSS")

这是情节:
library(ggplot2)
g <- ggplot(df, aes_string(x="group", fill="group")) +
geom_bar(aes(y = (..count..)/sum(..count..)))+
ylab("percent")
g + facet_wrap(~ choice)

This is how it looks so far

现在第一个条形显示:20%、20%、0%,但应该显示 40%、66.67% 和 0%(组中每个人的百分比,谁给出了这个答案)。

对于第二个条形图,应显示:30%、16.667% 和 75%。

第三条:30%、16.667% 和 25%

感谢您的帮助。

最佳答案

事先计算百分比可能更好:

library(dplyr)
dfl <- df %>%
group_by(group,choice) %>%
summarise(n=n()) %>%
group_by(group) %>%
mutate(perc=100*n/sum(n))

ggplot(dfl, aes(x=group, y=perc, fill=group)) +
geom_bar(stat="identity") +
ylab("percent") +
facet_wrap(~ choice)

这给出:
enter image description here

呈现数据的另一种(可能更好)方式是按组使用构面:
ggplot(dfl, aes(x=choice, y=perc, fill=choice)) +
geom_bar(stat="identity") +
ylab("percent") +
facet_wrap(~ group)

这给出:
enter image description here

关于r - 如何使用 facet_wrap 绘制 ggplot2,显示每个组的百分比,而不是整体百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30233590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com