在 ggplot 堆叠条形图上交错标签或仅添加选定标签

Staggering labels or adding only selected labels on ggplot stacked bar chart

我正在将一系列李克特量表问题绘制成堆叠条形图。它们需要被标记,但有些段是两个小段并且像下面的示例一样重叠(下面有示例代码)。是否有一种聪明的方法可以只标记足够大以适合标签的部分,或者可以错开标签的显示方式?

q1a<-rep(c("A", "B", "C", "D"), c(2, 5,45,45))
q1b<-rep(c("A", "B", "C", "D"), c(45,45,2, 5))
data<-data.frame(q1a,q1b)

data %>%
  select(q1a:q1b) %>%
  pivot_longer(cols = everything(), names_to = "Question") %>%
  filter(!is.na(value)) %>%
  count(Question, value) %>%
  group_by(Question) %>%
  mutate(Pct = n / sum(n)) %>%
  ggplot(aes(fill = value, x = Pct, y = fct_rev(Question))) +
  geom_bar(position = "fill", stat = "identity") +
  geom_text(aes(label = paste0(sprintf("%1.0f", Pct * 100), "%")), position = position_stack(vjust = 0.5), size = 3) +
  scale_fill_brewer(palette = "Blues") +
  theme_bw() +
  scale_x_continuous(labels = scales::percent) +
  labs(title = "Question 1", y = "Question", x = "Percentage") +
  theme(legend.title = element_blank())

如果我是你,我只会在 geom_text(aes()) 中使用 if_else() 显示大于 5% 的 Pct 标签。如果小于 5%,则不显示。

另外,由于你的geom_bar位置是fill,你也应该在geom_text中使用position = position_fill()对齐位置。

library(tidyverse)

data %>%
  select(q1a:q1b) %>%
  pivot_longer(cols = everything(), names_to = "Question") %>%
  filter(!is.na(value)) %>%
  dplyr::count(Question, value) %>%
  group_by(Question) %>%
  mutate(Pct = n / sum(n)) %>%
  ggplot(aes(fill = value, x = Pct, y = fct_rev(Question))) +
  geom_bar(position = "fill", stat = "identity") +
  geom_text(aes(label = if_else(Pct > 0.05, paste0(sprintf("%1.0f", Pct * 100), "%"), NULL)), 
            position = position_fill(vjust = 0.5), size = 3) +
  scale_fill_brewer(palette = "Blues") +
  theme_bw() +
  scale_x_continuous(labels = scales::percent) +
  labs(title = "Question 1", y = "Question", x = "Percentage") +
  theme(legend.title = element_blank())