leave empty space for legend in ggplot

Viewed 611

How can I make the plotting area the same in these two plots?

library(ggplot2)
ggplot(data=iris, mapping = aes(Sepal.Length, Sepal.Width)) + geom_point()
ggplot(data=iris, mapping = aes(Sepal.Length, Sepal.Width, col=Species)) + geom_point()

The goal is to overlay plots in an animation and I want the spacing to all be the same.

1 Answers

One way to reserve the space is to allow the legend to be created as it would be in the second plot but to set all the legend elements to be invisible against the background.

library(ggplot2)

ggplot(data=iris, mapping = aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point() +
  scale_color_manual(values = rep("black", 3)) +
  theme(legend.key = element_rect(fill = "white"), legend.text = element_text(color = "white"), legend.title = element_text(color = "white")) +
  guides(color = guide_legend(override.aes = list(color = NA)))

enter image description here

ggplot(data=iris, mapping = aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point()

enter image description here

Related