Spacing between legend keys in ggplot

ggplot2, r

Solution

Adding a margin to adjust `element_text`

mtcars %>%
  mutate(transmission = ifelse(am, "manual", "automatic")) %>%
  ggplot() +
  aes(x = transmission, fill = transmission) +
  geom_bar() +
  labs(fill = NULL) +
  theme(
    #legend.spacing.x = unit(.5, "char"), # adds spacing to the left too
    legend.position = "top",
    legend.justification = c(0, 0),
    legend.title = element_blank(),
    legend.margin = margin(c(5, 5, 5, 0)),
    legend.text = element_text(margin = margin(r = 10, unit = "pt")))

Problem

I have a legend on the top of the graph. I want the legend to be left aligned and to be able to set the spacing (1) between the aesthetic symbol (colored square) and the text and (2) between the text and the next aesthetic symbol. ``` library(tidyverse) mtcars %>% mutate(transmission = ifelse(am, "manual", "automatic")) %>% ggplot() + aes(x = transmission, fill = transmission) + geom_bar() + labs(fill = NULL) + theme( #legend.spacing.x = unit(.5, "char"), # adds spacing to the left too legend.position = "top", legend.justification = c(0,0), legend.title=element_blank(), legend.margin=margin(c(5,5,5,0))) ```

Original source

Related problems