w.Shen
w.Shen

Reputation: 41

How to remove extra space left by setting "theme(legend.title = element_blank())“ in ggplot2

there!

I want to remove legend title in ggplot2. I used legend.title = element_blank(), but there is still some extra space at the top of the legend box where the legend title originally was. Actually, I don't want that space. Anyone has ideas how to solve it? Thanks!

Here is the code to replicate the unwanted extra space:

library(ggplot2)
library(grid)
df1 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)

# A basic graph
lp <- ggplot(data=df1, aes(x=time, y=total_bill, group=sex, shape=sex)) + geom_line() + geom_point()

lp + theme(legend.title=element_blank(),
           legend.background = element_rect(colour = "black", size = 0.1),
           legend.key.size = unit(0.4, "lines"))

the code snippet is taken from http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/ with a little modification. The extra space exists between the first legend key and the top border of the legend box. I think it's because I resize the key size. When I remove `legend.key.size = unit(0.4, "lines"), everything is fine. However, I want to keep that line in my specific figure. I'm not sure if there is any way to solve that problem.

Upvotes: 3

Views: 2366

Answers (1)

Kent Thomas
Kent Thomas

Reputation: 61

theme(legend.margin=margin(t=-0.25,l=0.05,b=0.0,r=0.05, unit='cm'))

The negative moves the space inwards.

Upvotes: 6

Related Questions