使用ggplot2在图例上方和下方的空间

Mar*_*aph 15 r ggplot2

如果你看这里的图表!你可以看到传说上下有很多空白区域.我希望减少空间.

示例代码:

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)
Run Code Online (Sandbox Code Playgroud)

Len*_*ert 13

要删除图例的边距(负值会进一步减少空白区域):

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"))
Run Code Online (Sandbox Code Playgroud)

您还可以通过指定负数来删除绘图边距的下半部分(但请确保不要切断图例):

p + theme(plot.margin = unit(x = c(0, 0, -0.2, 0), units = "cm")
Run Code Online (Sandbox Code Playgroud)

插图:ggplot2,顶部和边缘的传奇


And*_*rie 5

以下是两个附加选项,可让您缩小图例周围的空间:

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

该选项plot.margin描述了情节本身周围有多少空间。第三个参数描述了绘图下方的空间量。将其设置为零会有帮助。

在此处输入图片说明