4
votes

I have a legend at the bottom of a graph in ggplot2, on two lines. I need to increase the horizontal space between items.

Currently the code is:

p + theme(legend.key = element_blank(), 
       legend.position = "bottom", 
       legend.title = element_blank(),
       legend.direction = "horizontal") + 
    guides(linetype = guide_legend(ncol = 3,keywidth=4))

But the resulting items are too close: enter image description here

Any suggestion?

1

1 Answers

5
votes

A bit of a hack:

#dummy data
df <- data.frame(x=1:20,
                 y=runif(20),
                 g=rep(c("a","long1","looonger1","xx"),5))


#suffix with spaces, make them same length
df$g <- substring(paste0(df$g,"                 "),1,15)

#plot as usual
ggplot(df,aes(x,y,linetype=g)) +
  geom_line() +
  theme(legend.key = element_blank(), 
        legend.position = "bottom", 
        legend.title = element_blank(),
        legend.direction = "horizontal") + 
  guides(linetype = guide_legend(ncol = 3,keywidth=4))

enter image description here