Mark Graph
Mark Graph

Reputation: 5121

The space above and below the legend using ggplot2

If you look at the charts here! you can see there is a lot of white space above and below the legend. I wish to reduce the amount of space.

Example code:

library(ggplot2)
library(gridExtra)
library(reshape)
library(plyr)
library(scales)

theme_set(theme_bw())

rows <- 1:nrow(faithful)
data <- cbind(faithful, rows)
molten <- melt(data, id.vars='rows', measure.vars=c('eruptions', 'waiting'))

p <- ggplot() +
    geom_line(data=molten, 
        mapping=aes(x=rows, y=value, group=variable, colour=variable), size=0.8) +
    scale_colour_manual(values=c('red','blue')) +
    opts(title='Title') +
    xlab(NULL) + ylab('Meaningless Numbers') +
    opts(
        legend.position='bottom',
        legend.direction='horizontal',
        legend.title=theme_blank(),
        legend.key=theme_blank(),
        legend.text=theme_text(size=9),
        legend.margin = unit(0, "line"),
        legend.key.height=unit(0.6,"line"),      
        legend.background = theme_rect(colour='white', size=0)
    )

ggsave(p, width=8, height=4, filename='crap.png', dpi=125)

Upvotes: 15

Views: 11830

Answers (2)

Lennert
Lennert

Reputation: 1034

To remove the margins of the legend (negative values reduce the white space even more):

p + theme(legend.margin=margin(t=0, r=0, b=0, l=0, unit="cm"))
p + theme(legend.margin=margin(t=0, r=0, b=-0.5, l=0, unit="cm"))

You can also remove the lower part of the plot margin by specifying negative numbers (but make sure that you don't cut off your legend):

p + theme(plot.margin = unit(x = c(0, 0, -0.2, 0), units = "cm"))

Illustrations: ggplot2, legend on top and margin

Upvotes: 16

Andrie
Andrie

Reputation: 179428

Here are two additional options that allow you to shrink the space surround the legend:

p + theme(
      legend.key.height=unit(0, "cm"),      
      plot.margin = unit(c(1,0.5,0,0.5), "lines")
    )

The option plot.margin describes how much space there is around the plot itself. The third argument describes the amount of space below the plot. Setting that to zero helps.

enter image description here

Upvotes: 5

Related Questions