没有标题的紧密传奇边界

时间:2017-08-27 11:39:27

标签: r ggplot2

当传奇没有头衔时,我想让传奇的边界变得更紧密。实际上,图例键上方有一个空白区域。我也喜欢边界是虚线。

ggplot2

该图基于以下代码:

library(ggplot2)
ggplot(temp, aes(x=diff_abs, y=emp_est_15, color=diff_sign)) + geom_point(shape=1, size=2) + 
  scale_colour_manual(values=c("green4", "red")) +
  scale_x_log10(breaks=10^(0:3)) + scale_y_log10(breaks=c(c(2,4,8) %o% 10^(0:3))) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
        panel.background = element_blank(), axis.line = element_line(colour = "black"),
        axis.text = element_text(color="black", size=13), axis.title = element_text(color="black", size=13),
        legend.key = element_blank(), legend.position=c(.2,.8), legend.box.background = element_rect(), 
        legend.background = element_blank()) +
  labs(x="\nGain ou perte d'emploi 2001-2015 (milliers, échelle log 10)", 
       y="Emploi 2015 (milliers, échelle log 10)\n", color="") 

2 个答案:

答案 0 :(得分:3)

正如Richard Telford在评论中提到的,设置legend.title = element_blank()将删除图例标题所占用的空间。因此“收紧”传说盒。

可以使用legend.box.background = element_rect(line = <some number other than 1>)

更改图例框的边框类型
# example using mtcars dataset
p <- ggplot(mtcars, aes(wt, mpg, col = factor(cyl)))
p + geom_point() +
  theme_bw() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        legend.key = element_blank(), legend.position=c(.8,.8), 
        legend.title = element_blank(),
        legend.box.background = element_rect(line = 3), 
        legend.background = element_blank())

enter image description here

答案 1 :(得分:1)

Z. Lin答案的小附录;通过设置legend.spacing.y = unit( 0, 'pt' )

可以消除顶部的剩余空白
p <- ggplot(mtcars, aes(wt, mpg, col = factor(cyl))) + geom_point() +
  theme_bw( base_size = 80 ) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        legend.key = element_blank(), legend.position=c( 0.5, 0.5 ), 
        legend.title = element_blank(),
        legend.box.background = element_rect(line = 3), 
        legend.background = element_blank() )
lgndA <- cowplot::get_legend( p )
lgndB <- cowplot::get_legend( p + theme( legend.spacing.y = unit( 0, 'pt' ) ) )
grid::grid.newpage()
cowplot::plot_grid( lgndA, lgndB )

Legends with different legend.spacing.y option in ggplot2