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

Lyn*_*ker 1 r graph ggplot2

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

在此输入图像描述

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())
Run Code Online (Sandbox Code Playgroud)

ben*_*n23 5

如果我是你,我只会显示Pct超过 5% 使用if_else()in的标签geom_text(aes())。如果低于 5%,则不显示任何内容。

另外,由于您的geom_bar位置是fill,因此您还应该使用position = position_fill()ingeom_text来对齐位置。

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())
Run Code Online (Sandbox Code Playgroud)

标签PCT