簡體   English   中英

將百分比標簽添加到堆疊條形圖

[英]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 之前對其進行聚合。

  1. 要正確處理數據:
  • questionresponse count
  • 按問題計算每個響應的道具
  1. Plot
  • map propy
  • 通過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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM