I'm trying to plot Likert-scale data on a divergent stacked bar chart with ggplot2
.
The legend is positioned horizontally at the bottom to match the order of the bars.
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
I'm using hrbrthemes::theme_ipsum_rc()
, which I'd really like to keep using.
But the spacing between the legend items seems to be very large, and proportional to the text's length:
I have tried various theme()
settings to attempt to reduce the spacing (see code), but I can't seem to find the source of this text-dependent spacing.
EDIT: As @chemdork123 & @marek-fiołka noted, it seems to come from the ggplot theme theme_ipsum_rc()
. I edited the question title, text, code and graph to reflect this.