用两个 ggplots 和普通图例绘制子图?

Plotly subplot with two ggplots and common legend?

我正在尝试安排两个转换为 plotly 对象的 ggplot 对象并使用一个通用图例。但是传说不知何故翻了一番:

df1 <- read.table(text = "group   x     y   
              group1 -0.212201  0.358867
              group2 -0.279756 -0.126194
              group3  0.186860 -0.203273
              group4  0.417117 -0.002592
              group1 -0.212201  0.358867
              group2 -0.279756 -0.126194
              group3  0.186860 -0.203273
              group4  0.186860 -0.203273", header = TRUE)

df2 <- read.table(text = "group   x     y   
              group1  0.211826 -0.306214
              group2 -0.072626  0.104988
              group3 -0.072626  0.104988
              group4 -0.072626  0.104988
              group1  0.211826 -0.306214
              group2 -0.072626  0.104988
              group3 -0.072626  0.104988
              group4 -0.072626  0.104988", header = TRUE)
library(dplyr)
library(ggplot2)
library(plotly)

p1 <- ggplot(df1, aes(x = x, y = y, colour = group)) +     
  geom_point(position = position_jitter(w = 0.04, h = 0.02), size = 1.8)

p2 <- ggplot(df2, aes(x = x, y = y, colour = group)) + 
  geom_point(position = position_jitter(w = 0.04, h = 0.02), size = 1.8)

subplot(ggplotly(p1), ggplotly(p2), nrows = 1)

我试过了

 subplot(ggplotly(p1), ggplotly(p2), nrows = 1) %>% layout(showlegend = FALSE)

但整个传说就这么消失了

我无法用两个单独的图修复双图例,但您可以将两个数据框组合起来制作一个多面图。不管图例问题如何,考虑到每个数据框中的分组变量相同,使用带有分面的单个数据框似乎是一种更自然的方法。在下面的示例中,我删除了小平面条以匹配您的示例,但您可以通过删除 theme 语句来保留它们。

p = ggplot(bind_rows(df1 %>% mutate(df="df1"), df2 %>% mutate(df="df2")),
       aes(x = x, y = y, colour = group)) +
  geom_point(position = position_jitter(w = 0.04, h = 0.02), size = 1.8) +
  facet_wrap(~ df, scales="free") +
  theme(strip.text=element_blank())

ggplotly(p)