[英]Adding percentage labels to a stacked barplot
I have successfully made a stacked barplot in R where the percentages add up to 100% for several different categories.我已经成功地在 R 中制作了一个堆叠条形图,其中几个不同类别的百分比加起来为 100%。 The dataframe looks like this:
数据框如下所示:
sujeito teste epentese vozeamento palavra tipo ortografia
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 a n 1 0 cats ts cs
2 b l 1 1 ducks ks cs
3 c l 1 1 cups ps cs
4 d l 0 0 grapes ps ces
5 e l 1 0 lakes ks ces
6 f n 1 0 gates ts ces
7 g n 0 0 books ks cs
8 h n 1 0 cakes ks ces
9 a n 1 1 kites ts ces
10 b n 1 0 boats ts cs
Then I used ggplot and deplyr to make a stacked barplot displaying these percentages.然后我使用 ggplot 和 deplyr 制作了一个显示这些百分比的堆叠条形图。 I used this code:
我使用了这个代码:
dados%>%
group_by(sujeito, epentese)%>%
summarise(quantidade = n())%>%
mutate(frequencia = quantidade/sum(quantidade))%>%
ggplot(., aes(x = sujeito, y = frequencia, fill = epentese))+
geom_col()+
geom_col(position = position_fill(reverse=TRUE))+
scale_y_continuous(labels=scales::percent)+
labs(title = "Epenthesis rates by subject")+
theme(plot.title = element_text(hjust = 0.5))+
xlab("Subject")+ylab("Frequency")
My intention, though, is to make it as the graph of the right side of this picture:不过,我的意图是将其作为这张图片右侧的图表:
I have tried different packages and also manipulating geom_text, but still no luck, especially due to the fact that I don't need the labels of both "fill categories", just the red one.我尝试了不同的包并操作 geom_text,但仍然没有运气,特别是因为我不需要两个“填充类别”的标签,只需要红色的标签。 I hope this isn't too redundant.
我希望这不是多余的。 Thanks in advance!
提前致谢!
To label only the red bars you could use eg an if_else
in geom_text
仅标注红柱可以使用例如一个
if_else
在geom_text
Additionally I removed the redundant geom_col()
and used some random example data.此外,我删除了多余的
geom_col()
并使用了一些随机示例数据。
library(ggplot2)
library(dplyr)
set.seed(42)
dados <- data.frame(
sujeito = sample(letters[1:8], 100, replace = TRUE),
epentese = sample(0:1, 100, replace = TRUE)
)
dados%>%
group_by(sujeito, epentese)%>%
summarise(quantidade = n())%>%
mutate(frequencia = quantidade/sum(quantidade))%>%
ggplot(aes(x = sujeito, y = frequencia, fill = factor(epentese))) +
geom_col(position = position_stack(reverse=TRUE))+
geom_text(aes(label = if_else(epentese == 0, scales::percent(frequencia, accuracy = 1), "")), vjust = 0, nudge_y = .01) +
scale_y_continuous(labels=scales::percent)+
labs(title = "Epenthesis rates by subject")+
theme(plot.title = element_text(hjust = 0.5))+
xlab("Subject")+ylab("Frequency")
#> `summarise()` regrouping output by 'sujeito' (override with `.groups` argument)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.