mindlessgreen
mindlessgreen

Reputation: 12112

Combined centered legend

I am using patchwork to create a combined plot with a common legend that is centered on the top.

library(ggplot2)
library(patchwork)

x1 <- ggplot(iris,aes(Sepal.Width, Petal.Length, col=Species))+
       geom_point()

x2 <- ggplot(iris,aes(Petal.Width, Petal.Length, col=Species))+
       stat_ellipse(show.legend=F)

wrap_plots(x1, x2, guides="collect") +
  theme(legend.position="top",
        legend.direction="horizontal")

This is what I get.

enter image description here

This is what I was expecting.

ggpubr::ggarrange(x1, x2, common.legend=T)

enter image description here

Upvotes: 1

Views: 88

Answers (1)

stefan
stefan

Reputation: 124183

The issue is that you are using + instead of &. See here for the differences between operators:

  1. With + the theme layer is only applied to the last plot, i.e. x2 in your case which has no legend
  2. If you want to apply to all plots you have to make use of &
library(ggplot2)
library(patchwork)

x1 <- ggplot(iris,aes(Sepal.Width, Petal.Length, col=Species))+
  geom_point()

x2 <- ggplot(iris,aes(Petal.Width, Petal.Length, col=Species))+
  stat_ellipse(show.legend=F)

wrap_plots(x1, x2, guides="collect") &
  theme(legend.position="top",
        legend.direction="horizontal")

Upvotes: 1

Related Questions