spore234
spore234

Reputation: 3640

Add more space between ggplot legend items

I have data like this

plot.d <- data.frame(vars = c(11:20),
                       time = c(1:5,1:5),
                       method = c(rep("aaaa", 5), rep("bbbb", 5)))

Now I want to create a point plot, the legend should be 1 column, but with increased space.

According to the manual, legend.spacing.y should do the trick. However, using this code:

ggplot(plot.d, aes(y = vars, x = time)) +
  geom_point(aes(shape= method, color = method, size = method)) +
  scale_shape_manual(values=c(18,15), guide=guide_legend(nrow=2)) +
  scale_color_manual(values=c('grey60','grey50')) +
  scale_size_manual(values=c(3, 2)) +
  theme(legend.title = element_blank(),
    legend.spacing.x = unit(0.15, 'cm'),
    legend.spacing.y = unit(1.4, 'cm'),
    legend.text=element_text(size=12),
    legend.box.background = element_rect(colour = "black")
  )

I only get this plot:

enter image description here

The box around the legend is increased but the line spacing between the two legend items remains the same.

What's wrong here?

Upvotes: 1

Views: 337

Answers (1)

NelsonGon
NelsonGon

Reputation: 13309

If I got the aim well, you need to modify legend.key.*. An example with random choices:

   ggplot(plot.d, aes(y = vars, x = time)) +
  geom_point(aes(shape= method, color = method, size = method)) +
  scale_shape_manual(values=c(18,15), guide=guide_legend(nrow=2)) +
  scale_color_manual(values=c('grey60','grey50')) +
  scale_size_manual(values=c(3, 2)) +
  theme(legend.title = element_blank(),
        legend.spacing.x = unit(0.15, 'cm'),
        legend.spacing.y = unit(1.2, 'cm'),
        legend.text=element_text(size=12),
        legend.key.width = unit(1.5,"cm"),
        legend.key.height = unit(1.2,"cm"),
        legend.box.background = element_rect(colour = "black")
  )

Result: enter image description here

Upvotes: 2

Related Questions