Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

r - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...