Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spacing between legend keys in ggplot

Tags:

r

ggplot2

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

like image 767
sharoz Avatar asked Aug 10 '18 07:08

sharoz


1 Answers

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

like image 108
mpalanco Avatar answered Oct 02 '22 01:10

mpalanco