Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2, legend on top and margin

Consider the following:

library(ggplot2) library(grid) ggplot(diamonds, aes(clarity, fill=cut)) +    geom_bar() +      theme(     plot.margin=unit(x=c(0,0,0,0),units="mm"),     legend.position="top",     plot.background=element_rect(fill="red")) +   guides(fill=guide_legend(title.position="top")) 

The output of that looks something like this: ggplot2 output In the context of plot.margin=unit(x=c(0,0,0,0),units="mm") there's an unseemly amount of white (red) space above the legend. Does anyone know how to remedy that?

Thanks for any hint.

Sincerely, Joh

like image 729
balin Avatar asked Jun 12 '13 19:06

balin


2 Answers

Like you said, I can't see it in your example, but I'm guessing the margin is of the legend itself. You can eliminate the margin around the legend itself by adding:

+ theme(legend.margin=margin(t = 0, unit='cm')) 

This applies to ggplot2 v2.1.0 or higher. Note that, at least for now, the old solution still works as well:

+ theme(legend.margin=unit(-0.6,"cm")) # version 0.9.x 

like image 164
sc_evans Avatar answered Sep 23 '22 19:09

sc_evans


If I exaggerate the margins for more visibility, and run showViewports, I get the following:

p + guides(fill=guide_legend(keyheight=unit(1,"cm"))) + theme(plot.margin=unit(c(1,1,1,1),"cm")) showViewport(col="black",label=TRUE, newpage=TRUE, leaves=FALSE) 

enter image description here

from which it would appear that the non-existent title is somehow taking space.

Edit: nope, it's just an unfortunate overlap of the labels. It's not the title.

Let's look at the legend itself, which seems to be causing the problem.

library(gtable) g = ggplotGrob(p) leg = gtable_filter(g, "guide") plot(leg) leg$heights # sum(0.5lines, sum(1.5mm, 10mm, 0mm, 1.5mm), 0.5lines)+0cm grid.rect(height=leg$heights)  grid.rect(height=leg$heights - unit(1,"line"), gp=gpar(lty=2)) 

so, indeed, it's the legend that's adding some margins (0.5 + 0.5 = 1 line in total). I reckon it's a missing guide.margin option in the theme, that is being replaced by a default value of half a line.

enter image description here

like image 20
baptiste Avatar answered Sep 22 '22 19:09

baptiste