ggplot2
ggplot2 copied to clipboard
Remove space for legend title if it doesn't have a title
If a guide has a label, you can make it flush with the edge of a plot:
ggplot(PlantGrowth) +
aes(x=group, y=weight, fill=group) +
geom_boxplot() +
theme(
legend.position="top",
legend.justification = "left",
legend.margin = margin(0, 0, 0, 0))

But if you set the label to NULL, a there is a gap or misalignment that doesn't seem to be removable:
ggplot(PlantGrowth) +
aes(x=group, y=weight, fill=group) +
geom_boxplot() +
labs(fill = NULL) + # removes legend title
theme(
legend.position="top",
legend.justification = "left",
legend.margin = margin(0, 0, 0, 0))

It looks like a unit of legend.spacing.x is inserted even if the name is missing.
library(ggplot2)
ggplot(PlantGrowth) +
aes(x=group, y=weight, fill=group) +
geom_boxplot() +
labs(fill = NULL) + # removes legend title
theme(
legend.position="top",
legend.justification = "left",
legend.margin = margin(0, 0, 0, 0),
legend.spacing.x = unit(0, "pt")
)

You can work around this issue by placing some spaces before and after the labels, so that setting legend.spacing.x to zero doesn't cause problems.
ggplot(PlantGrowth) +
aes(x=group, y=weight, fill=group) +
geom_boxplot() +
scale_fill_hue(
name = NULL,
labels = function(x) paste0(" ", x, " ")
) +
theme(
legend.position="top",
legend.justification = "left",
legend.margin = margin(0, 0, 0, 0),
legend.spacing.x = unit(0, "pt")
)

The legend drawing code is a bit of a mess, so I don't see an immediate approach to fixing this more generally.
Thanks for the workaround!
Actually, here is a better approach. Just set the margins of legend.text appropriately.
In general, I'd like to get rid of legend.spacing.* altogether and just use margins on legend title and text to format the legend, but that requires different settings depending on whether the legend is laid out horizontally or vertically.
library(ggplot2)
ggplot(PlantGrowth) +
aes(x=group, y=weight, fill=group) +
geom_boxplot() +
labs(fill = NULL) + # removes legend title
theme(
legend.position="top",
legend.justification = "left",
legend.margin = margin(0, 0, 0, 0),
legend.spacing.x = unit(0, "pt"),
legend.text = element_text(size = rel(0.8), margin = margin(0, 11, 0, 5.5))
)

Created on 2019-10-27 by the reprex package (v0.3.0)
+1!
I believe the extra spacing can be removed with legend.box.spacing = unit(0, "pt").
library(ggplot2)
ggplot(PlantGrowth) +
aes(x = group, y = weight, fill = group) +
geom_boxplot() +
labs(fill = NULL) + # removes legend title
theme(
legend.position = "top",
legend.justification = "left",
legend.margin = margin(0, 0, 0, 0),
legend.spacing.x = unit(0, "pt"),
legend.box.spacing = unit(0, "pt")
)