[英]Adding percentage labels to stacked barplot
我想使用 ggplo2 将百分比标签添加到堆叠条形图。 这是我的代码。 到目前为止它不起作用。
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))
这是我的数据片段:
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"))
基本上你在正确的轨道上。 最简单的方法可能是在将数据集传递给 ggplot2 之前对其进行聚合。
question
和response
count
prop
在y
上geom_text
向条形添加百分比标签。 由于我们有一个堆叠条形图,我们必须将标签的 position 也设置为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.