[英]Adding percentage labels to stacked barplot
I would like to add percentage labels to stacked barplot using ggplo2.我想使用 ggplo2 将百分比标签添加到堆叠条形图。 Here is my code.
这是我的代码。 It does not work so far.
到目前为止它不起作用。
df <- longer_data %>%
drop_na(response) %>%
group_by(question) %>%
count(response) %>%
mutate(prop = percent(response / sum(response))) %>%
mutate(response = factor(response, levels = 1:3, labels = c("Yes", "No", "I don't know"))) %>%
mutate(prop = percent(response / sum(response))) %>%
ggplot(df, aes(x = question, fill = response)) +
geom_bar(stat= "count", position = "fill") +
labs(title =" Please indicate which part of the driving task shown on the interface are \n performed by the car or you, the driver of the car.", subtitle =" Speed and distance control" )+scale_fill_manual(values = c("Yes" = "Forestgreen", "No" = "Darkred", "I don't know" = "Grey")) +labs(x ="HMIs", y = "Percentage") +scale_y_continuous(labels = scales::percent) +theme(axis.text.x = element_text(angle = 360, hjust = 0))
Here is a snippet of my data:这是我的数据片段:
structure(list(question = c("HMI1", "HMI2", "HMI3", "HMI4", "HMI5",
"HMI6", "HMI1", "HMI2", "HMI3", "HMI4"), response = c("1", "1",
"1", "1", "1", "1", "1", "1", "1", "3")),
row.names = c(NA, -10L ), class = c("tbl_df", "tbl", "data.frame"))
Basically you were on the right track.基本上你在正确的轨道上。 Easiest way is probably to aggregate your dataset before passing it to ggplot2.
最简单的方法可能是在将数据集传递给 ggplot2 之前对其进行聚合。
count
by question
and response
question
和response
count
prop
on y
prop
在y
上geom_text
.geom_text
向条形添加百分比标签。 As we have a stacked bar chart we have to set the position for the labels also to position_stack
where I used vjust =.5
to put the labels in the middle of each bar.position_stack
,我使用vjust =.5
将标签放在每个条形的中间。library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)
df <- longer_data %>%
drop_na(response) %>%
count(question, response) %>%
group_by(question) %>%
mutate(prop = n / sum(n),
response = factor(response, levels = 1:3, labels = c("Yes", "No", "I don't know")))
ggplot(df, aes(x = question, y = prop, fill = response)) +
geom_col() +
geom_text(aes(label = percent(prop)), position = position_stack(vjust = .5)) +
labs(title = " Please indicate which part of the driving task shown on the interface are\nperformed by the car or you, the driver of the car.",
subtitle = " Speed and distance control") +
scale_fill_manual(values = c("Yes" = "Forestgreen", "No" = "Darkred", "I don't know" = "Grey")) +
labs(x = "HMIs", y = "Percentage") +
scale_y_continuous(labels = scales::percent) +
theme(axis.text.x = element_text(angle = 360, hjust = 0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.