9

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)))

enter image description here

aosmith
  • 32,788
  • 7
  • 75
  • 108
sharoz
  • 5,953
  • 7
  • 30
  • 54
  • 1
    Possible duplicate of [ggplot2 increase space between legend keys](https://stackoverflow.com/questions/32275113/ggplot2-increase-space-between-legend-keys) – erc Aug 10 '18 at 08:01
  • s. here: https://stackoverflow.com/questions/11366964/is-there-a-way-to-change-the-spacing-between-legend-items-in-ggplot2/26971729 – erc Aug 10 '18 at 08:04

1 Answers1

10

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")))

enter image description here

mpalanco
  • 11,967
  • 2
  • 55
  • 64