[英]R stacked percentage bar plot with percentage of binary factor and labels (with ggplot)
[英]R Stacked percentage bar plot with percentage of two factor variables with ggplot
我试图绘制两个因子变量,并在图中用 % 标记结果。
我已经检查了这篇文章和他/她提供的链接:
您在这里看到的 ggplot 行实际上来自推荐的帖子之一:
sex <- c("F","F","M", "M", "M", "F","M","F","F", "M", "M", "M", "M","F","F", "M", "M", "F")
behavior <- c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "B", "C", "A")
BehSex <- data.frame(sex, behavior)
ggplot(BehSex, aes(x= factor(sex), fill= factor(behavior), y = (..count..)/sum(..count..)))+
geom_bar() +
stat_bin(geom = "text",
aes(label = paste(round((..count..)/sum(..count..)*100), "%")),
vjust = 5)
但是,当我使用该行时,出现以下错误:
错误:StatBin 需要一个连续的 x 变量:x 变量是离散的。 也许你想要 stat="count"?
我尝试在 geom_bar() 中使用 stat="count" 但它似乎没有按预期工作。
三个问题:
1)我做错了什么?
2)我怎样才能绘制出我想要的图?
3)我如何绘制:百分比,然后在另一个图中绘制计数?
这是我现在的情节
预先感谢您的帮助!
关于您提到的帖子的答案,您必须使用position = position_stack()
显示百分比。
此外,您可以使用dplyr
包从数据dplyr
获取百分比。 在我看来,显示标签更容易:
library(dplyr)
df <- BehSex %>% group_by(sex) %>% count(behavior) %>% mutate(Percent = n / sum(n)*100)
# A tibble: 6 x 4
# Groups: sex [2]
sex behavior n Percent
<fct> <fct> <int> <dbl>
1 F A 2 25
2 F B 3 37.5
3 F C 3 37.5
4 M A 4 40
5 M B 3 30
6 M C 3 30
然后,你可以像这样得到你的情节:
ggplot(df, aes(x = sex, y = Percent, fill = behavior))+
geom_bar(stat = "identity")+
geom_text(aes(label = paste(Percent,"%"), y = Percent),
position = position_stack(vjust = 0.5))+
coord_flip()+
labs(x = "Sex", y = "Percentage",fill = "Behavior")
这是使用dplyr
进行一些数据准备的另一种方法:
编辑:添加计数。 要显示其中一个,只需更改标签即可。
library(dplyr)
BehSexSum <- BehSex %>%
count(sex, behavior) %>%
mutate(pct = n / sum(n),
pct_label = scales::percent(pct))
ggplot(BehSexSum, aes(x= sex, fill = behavior, y = pct)) +
geom_col() +
geom_text(aes(label = paste(pct_label, n, sep = "\n")),
lineheight = 0.8,
position = position_stack(vjust = 0.5)) +
scale_y_continuous(labels = scales::percent)
我认为将 y 轴标签格式化为百分比的更简单方法是使用scale_y_continuous(labels = scales::percent)
,而不是使用stat_bin(...)
。 因此,代码几乎可以保持不变。
ggplot(BehSex, aes(x= factor(sex), fill= factor(behavior), y =(..count..)/sum(..count..)))+
geom_bar() +
#Set the y axis format as percentage
scale_y_continuous(labels = scales::percent)+
#Change the legend and axes names
labs(x = "Sex", y = "Percentage",fill = "Behavior")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.