0

I want to know how to increase the space between legend items in ggplot. This comes in handy when you have more involved plots and the viewer needs a clear legend of a color gradient, which is sometimes hard to see when you don't have enough whitespace between the parts of a color gradient.

REPREX

data(iris)

iris$Sepal.Length.cut<-cut(iris$Sepal.Length, breaks=seq(4,8,1), labels=c("here","and here","here too", "here three"))

iris.grad<-colorRampPalette(c("darkgoldenrod","darkgoldenrod4"))
iris.col<-iris.grad(4)
names(iris.col)<-levels(iris$Sepal.Length.cut)

ggplot(iris)+
  geom_bar(aes(x=Species,fill=Sepal.Length.cut), stat="count")+
  scale_fill_manual(values=iris.col, name="increase space \n where indicated")+
  theme(legend.spacing.y=unit(1.5,"lines"))

legend.spacing.y only increases the space between the title and the legend elements, increasing the key size doesn't get rid of the problem. Interestingly enought this solution actually says it should and their reprex works for me... maybe its the difference between bars and points?

Gmichael
  • 526
  • 1
  • 5
  • 16

1 Answers1

2

You can do this by specifying guide_legend(byrow = TRUE) before adding the spacing to your theme.

ggplot(iris) +
  geom_bar(aes(Species, fill = Sepal.Length.cut), stat = "count") +
  scale_fill_manual(values=iris.col, name = "increase space \n where indicated") +
  guides(fill = guide_legend(byrow = TRUE)) +
  theme(legend.spacing.y = unit(1.5, "lines"))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • ahhhh, yes, in my original (not reprex) I had also specified the guide via scale_fill_manual and that created a conflict. I didn't even think to reproduce that somehow! – Gmichael Jan 27 '22 at 08:33