Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make legend invisible but keep figure dimensions and margins the same

Tags:

r

ggplot2

I have made a plot with a legend.

enter image description here

Using an image editing program I made the legend invisible (but otherwise the figure has the same dimensions)

enter image description here

Is it possible to do this in ggplot2? I want to have a 2x2 panel of diagrams in a document but only one legend.

like image 357
slabofguinness Avatar asked Feb 24 '17 12:02

slabofguinness


2 Answers

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

like image 99
Robert Hering Avatar answered Oct 02 '22 12:10

Robert Hering


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.

like image 33
nrussell Avatar answered Oct 02 '22 11:10

nrussell