4
votes

My question is an extension of this question. Note that I'm using version 2.3.0 which is available on github, not yet on CRAN.

library(ggplot2)

df <- data.frame("Categories" = rep(c("A", "B", "C"), 3),  
                 "values" = c(rep(0.39, 3), rep(0.37, 3), rep(0.24, 3)),
                 "X" = 1:9)

ggplot(df, aes(x = X, y = values, colour = Categories)) +
  geom_line() +
  theme(
        legend.position = "top",
        legend.spacing.x = unit(2, unit = "cm"),
        legend.title = element_blank()
        ) 

The code above creates this plot.

enter image description here

I would like to move the legend labels (A, B, C) closer to their corresponding icons, as shown by the red arrows below, which would create more whitespace between the legend categories. How would I do that?

enter image description here

1
Can you not reduce legend.spacing.x?Tung
legend.text.align = unit(-1, unit = "cm") - help page suggest it take a number but doesnt seem to work unless a unituser2957945
@Tung the point of the question is to increase the whitespace in between the legend keys.Phil
@user2957945 Tried that - didn't seem to make a difference.Phil

1 Answers

6
votes

One possible workaround is to add extra whitespace on the right of Categories using stringr::str_pad

library(ggplot2)

df <- data.frame("Categories" = rep(c("A", "B", "C"), 3),  
                 "values" = c(rep(0.39, 3), rep(0.37, 3), rep(0.24, 3)),
                 "X" = 1:9)

# define a custom function
str_pad_custom <- function(labels){
  new_labels <- stringr::str_pad(labels, 10, "right")
  return(new_labels)
}

ggplot(df, aes(x = X, y = values, colour = Categories)) +
  geom_line() +
  scale_color_brewer(labels  = str_pad_custom,
                     palette = "Dark2") +
  theme(
    legend.position = "top",
    legend.key.width = unit(1.0,  unit = "cm"),
    legend.spacing.x = unit(0.25, unit = "cm"),
    legend.title = element_blank()
  ) 

Created on 2018-06-15 by the reprex package (v0.2.0).