减少ggplot2水平图例中项目之间的间距

Reducing spacing between items in ggplot2 horizontal legend

我正在尝试用 ggplot2 上绘制 Likert-scale 数据。 图例 水平放置 在底部以匹配条形的顺序。

library(tidyverse)
library(hrbrthemes)

# Sample data
data <- tibble(
        item = rep(c("A", "B", "C", "D", "E"), each = 5),
        resp = rep(c("Strongly disagree", "Disagree", "Neither agree nor disagree", "Agree", "Strongly agree"), 5) %>% 
            factor(head(., 5), ordered = T),
        count = sample(1:10, 25, replace = T)) %>% 
    mutate(count = if_else(resp == "Neither agree nor disagree", count/2, as.double(count)))

# Divergent stacked bar chart
data %>% 
    ggplot(aes(item, count, fill = resp, order = resp)) +
    geom_col(data = filter(data, !(resp %in% c("Strongly disagree", "Disagree"))),
                     position = position_stack(reverse = T)) +
    geom_col(aes(y = -count),
                     filter(data, !(resp %in% c("Agree", "Strongly agree")))) +
    scale_fill_brewer(palette = "RdBu", drop = F) +
    labs(y = NULL) +
    coord_flip() +
    theme_ipsum_rc() +
    theme(legend.position="bottom",
          legend.spacing.x = unit(0.1, "cm"), # reduces margin around text, but not the right spacing
          legend.text = element_text(margin = margin(0,0,0,0)), # no effect
          legend.margin=margin(c(0,0,0,0)))                     # no effect

我正在使用 hrbrthemes::theme_ipsum_rc(),我真的很想继续使用它。

但是图例项之间的间距似乎很大,并且与文本的长度成正比:

我尝试了各种 theme() 设置来尝试减小间距(参见代码),但我似乎无法找到此 text-dependent 间距的来源。

编辑:正如@chemdork123 和@marek-fiołka 指出的那样,它似乎来自 ggplot 主题 theme_ipsum_rc()。我编辑了问题标题、文本、代码和图表以反映这一点。

对我来说,你的代码给出了这个结果

library(tidyverse)
# Sample data
data <- tibble(
  item = rep(c("A", "B", "C", "D", "E"), each = 5),
  resp = rep(c("Strongly disagree", "Disagree", "Neither agree nor disagree", "Agree", "Strongly agree"), 5) %>% 
    factor(head(., 5), ordered = T),
  count = sample(1:10, 25, replace = T)) %>% 
  mutate(count = if_else(resp == "Neither agree nor disagree", count/2, as.double(count)))

# Divergent stacked bar chart
data %>% 
  ggplot(aes(item, count, fill = resp, order = resp)) +
  geom_col(data = filter(data, !(resp %in% c("Strongly disagree", "Disagree"))),
           position = position_stack(reverse = T)) +
  geom_col(aes(y = -count),
           filter(data, !(resp %in% c("Agree", "Strongly agree")))) +
  scale_fill_brewer(palette = "RdBu", drop = F) +
  labs(y = NULL) +
  coord_flip() +
  theme(legend.position="bottom")

也许您的软件包版本已过时。 我的 tidyverse 包是版本 1.3.1

感谢@chemdork123,我意识到它实际上不是由 ggplot2hrbrthemes 引起的。

似乎加载这个奇怪间距的罪魁祸首

library(showtext)
showtext_auto()

能够使用特殊字体(例如 theme_ipsum_rc() 使用的 Roboto Condensed)。

showtext_end() 停止它实际上解决了问题并删除了图例项之间不需要的间距。