ggplot 用 geom_bar 中的百分比替换计数 [英] ggplot replace count with percentage in geom_bar
本文介绍了ggplot 用 geom_bar 中的百分比替换计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框 d
:
> head(d,20)
groupchange Symscore3
1 4 1
2 4 2
3 4 1
4 4 2
5 5 0
6 5 0
7 5 0
8 4 0
9 2 2
10 5 0
11 5 0
12 5 1
13 5 0
14 4 1
15 5 1
16 1 0
17 4 0
18 1 1
19 5 0
20 4 0
我正在与:
ggplot(d, aes(groupchange, y=..count../sum(..count..), fill=Symscore3)) +
geom_bar(position = "dodge")
通过这种方式,每个条形代表其在整个数据中的百分比.
In this way each bar represents its percentage on the whole data.
相反,我希望每个条形代表一个相对百分比;即用 groupchange = k
获得的条形总和应该是 1
.
Instead I would like that each bar represents a relative percentage; i.e. the sum of the bar in obtained with groupchange = k
should be 1
.
推荐答案
首先汇总和转换您的数据:
First summarise and transform your data:
library(dplyr)
d2 <- d %>%
group_by(groupchange, Symscore3) %>%
summarise(count = n()) %>%
mutate(perc = count/sum(count))
然后你可以绘制它:
ggplot(d2, aes(x = factor(groupchange), y = perc*100, fill = factor(Symscore3))) +
geom_bar(stat="identity", width = 0.7) +
labs(x = "Groupchange", y = "percent", fill = "Symscore") +
theme_minimal(base_size = 14)
这给出:
或者,您可以使用 scales
包中的 percent
函数:
Alternatively, you can use the percent
function from the scales
package:
brks <- c(0, 0.25, 0.5, 0.75, 1)
ggplot(d2, aes(x = factor(groupchange), y = perc, fill = factor(Symscore3))) +
geom_bar(stat="identity", width = 0.7) +
scale_y_continuous(breaks = brks, labels = scales::percent(brks)) +
labs(x = "Groupchange", y = NULL, fill = "Symscore") +
theme_minimal(base_size = 14)
给出:
这篇关于ggplot 用 geom_bar 中的百分比替换计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文