Reputation: 982
I'd like to make the border around a legend tighter when the legend has no title. As it is, there is a blank space above the legend key. I'd also like the border to be a dotted line.
The plot is based on the following code:
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="")
Upvotes: 0
Views: 540
Reputation: 171
A small addendum to Z. Lin answer; one can get rid of the remaining blank space on the top by setting 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
Upvotes: 1
Reputation: 29085
As Richard Telford mentioned in the comment, setting legend.title = element_blank()
will remove the space occupied by legend title & hence "tighten" the legend box.
Legend box's border type can be changed with 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())
Upvotes: 4