【问题标题】:The space above and below the legend using ggplot2使用ggplot2的图例上方和下方的空间
【发布时间】:2012-08-31 08:48:46
【问题描述】:

如果您查看图表here!您可以看到图例上方和下方有很多空白区域。我希望减少空间量。

示例代码:

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)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

    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"))
    

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

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

    插图:ggplot2, legend on top and margin

    【讨论】:

    【解决方案2】:

    这里有两个额外的选项可以让您缩小图例周围的空间:

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

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

    【讨论】:

    • 所以从根本上说,你是在告诉我在我无法摆脱的传说周围有 apdding?我只能让其中一些看起来不存在。
    • 我并不是说有你无法摆脱的填充。我只是说我的解决方案是我能做的最好的。毫无疑问,其他人可以做得更好。
    猜你喜欢
    • 2015-12-15
    • 2017-12-26
    • 2017-12-14
    • 2016-01-10
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多