Sonu Mishra
Sonu Mishra

Reputation: 1779

Reduce padding in ggplot2 legend

I am trying to obtain a graph using ggplot2. The problem is that I am not able to reduce the white-space between the legend border and the text. For example: sample legend,

In this, I want to reduce the white space at the top that I have marked with some curly lines.

I searched a lot, but at most places, the answers suggest to reduce the key.height or key.width, but that is not what I want; I am pretty happy with those. I just want to get rid of the white space at the top.

Upvotes: 10

Views: 13591

Answers (2)

Lennart Van der Goten
Lennart Van der Goten

Reputation: 119

The other solutions have not worked in my case as there was still whitespace at the top.

Setting

theme(legend.title=element_blank(),
      legend.margin = margin(0, 0, 0, 0),
      legend.spacing.x = unit(0, "mm"),
      legend.spacing.y = unit(0, "mm"))

removed all the white space.

Upvotes: 8

eipi10
eipi10

Reputation: 93761

You can remove the space for the legend title with:

theme(legend.title=element_blank())

If that's not sufficient then do:

theme(legend.title=element_blank(),
      legend.margin=margin(c(1,5,5,5)))

and play around with the values (they're in the order top, right, bottom, left) until you get something you like.

Upvotes: 17

Related Questions