Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left align legend labels with ggplot

Tags:

r

ggplot2

I have a legend that looks like this:

Legend exemple

It is somewhat confusing that, e.g., the "color-a" label is exactly centered between the point at its left and the point at its right. I would like this label to be closer from the points at its left to make it obvious which label is associated with what point.

I have tried to use legend.key.width, legend.title.align, legend.spacing.x with no luck so far...

Here is a minimal reproducible example:

library(tidyverse)

# Test data, it does not matter.
data <- tibble(
  color = c(rep('color-a', 5), rep('color-b', 5), rep('color-c', 5), rep('color-d', 5)),
  x = rep(seq(0, 4, 1), 4),
  y = c(seq(0, .4, 0.1), seq(0, .4, 0.1) + 0.1, seq(0, .4, 0.1) + 0.3, seq(0, .4, 0.1) + 0.4)
)

# Plot
ggplot(data, aes(x = x, y = y, color = color)) +
  scale_color_discrete(guide="legend") +
  geom_point() +
  theme_minimal() +
  theme(legend.position = "bottom")
like image 656
Quentin Roy Avatar asked Sep 12 '19 00:09

Quentin Roy


1 Answers

You can't left align them more than they already are. But, you can set a margin, to create more space between one the right side of the text:

ggplot(data, aes(x = x, y = y, color = color)) +
  scale_color_discrete(guide='legend') +
  geom_point() +
  theme_minimal() +
  theme(
    legend.position = "bottom", 
    legend.text = element_text(margin = margin(0, 50, 0, 0))) ## <- here
  )

enter image description here

like image 134
Axeman Avatar answered Oct 21 '22 09:10

Axeman