Make legend invisible but keep figure dimensions and margins the same

Making the elements just white could cause problems, i.e. in cases of continuous scales or so. One may makes the scales and text elements just invisible.

p <- ggplot(mtcars, aes(x = disp, y = hp, lty = factor(gear))) +
          geom_point(aes(color = cyl)) +
          geom_line()

Gives a normal plot with legend:

enter image description here

Now make it really "invisible" by setting alpha = 0 in override.aes = list() within the guide = guide_legend() argument for each of the scales and color = "transparent" for the text elements of the legend:

p + scale_color_continuous(guide = guide_legend(override.aes = list(alpha = 0) ) )+
scale_linetype(guide = guide_legend(override.aes = list(alpha = 0) ) )+
theme(legend.title = element_text(color = "transparent"),
    legend.text = element_text(color = "transparent"))

enter image description here


Using this as an example,

library(ggplot2)

p <- ggplot(mtcars, aes(x = disp, y = hp, color = factor(cyl))) +
    geom_point() +
    geom_line()

enter image description here

The following seems to work:

p + theme(
        legend.text = element_text(color = "white"),
        legend.title = element_text(color = "white"),
        legend.key = element_rect(fill = "white")
    ) + 
    scale_color_discrete(
        guide = guide_legend(override.aes = list(color = "white"))
    )

enter image description here

Notice that the dimension of the gray plot area did not change.

Tags:

R

Ggplot2