2019-06-06

Spacing between legend keys in ggplot2

Problem

We want to add some spacing between the elements of the legend to the following plot using ggplot2.

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

Solution

  • First option: spacing between the 4 elements
  • We use legend.spacing.x to add the spacing between the 4 elements the legend's key and 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"),
        legend.position = "top",
        legend.justification = c(0, 0),
        legend.title = element_blank(),
        legend.margin = margin(c(5, 5, 5, 0)))
    
  • Second option: spacing between the 2 groups automatic and manual
  • We pass the argument margin to he element_text function to add spacing only between the 2 groups, the two types of transmissions automatic and manual, between the text automatic and the key (blue square) of manual

    mtcars %>%
      mutate(transmission = ifelse(am, "manual", "automatic")) %>%
      ggplot() +
      aes(x = transmission, fill = transmission) +
      geom_bar() +
      labs(fill = NULL) +
      theme(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")))
    

    Related posts

    References

    No hay comentarios:

    Publicar un comentario

    Nube de datos