Gmichael
Gmichael

Reputation: 568

Spacing of Legend Items in ggplot

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?

Upvotes: 1

Views: 4152

Answers (2)

JVGen
JVGen

Reputation: 601

UPDATE
As of ggplot2 3.5.0, spacing between key/labels within a legend is controlled by legend.key.spacing.x and legend.key.spacing.y.

This post provides updated information.

Posting for anyone else that lands here and is looking for a solution.

Upvotes: 7

Allan Cameron
Allan Cameron

Reputation: 174506

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

Upvotes: 2

Related Questions