nohomejerome
nohomejerome

Reputation: 141

R: Increase vertical spacing between legend items using ggplot

I created a line chart using ggplot. I want to increase the vertical spacing between my legend items (text and symbols)

I found this about this problem. However, isn't there a more simple (i.e. without writing a function) solution to this problem?

I tried the command legend.spacing.y but that only moves the entire legend up and down and not the spacing between the items.

Also, I tried: theme(legend.text = element_text(margin = margin(t = 1, unit = "cm")))) However, this only moves the text and not the items.

Could anybody please help?

Thanks!

Upvotes: 1

Views: 615

Answers (2)

akrun
akrun

Reputation: 887118

We can also do this in a pipe with tidyverse

library(ggplot2)
library(dplyr)
mtcars %>%
    mutate(cyl = factor(cyl)) %>%
    ggplot(aes(mpg, wt, colour = cyl)) +
   geom_point() +
  theme(
        legend.key.size = unit(1.5, 'lines'),
        legend.key = element_rect(size = 5, color = 'white'))

Upvotes: 1

Duck
Duck

Reputation: 39595

This can be useful:

library(ggplot2)
#Code
ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() +
  theme(
        legend.key.size = unit(1.5, 'lines'),
        legend.key = element_rect(size = 5, color = 'white'))

Output:

enter image description here

Upvotes: 0

Related Questions