Plotly subplot with two ggplots and common legend?

2019-07-03 10:55发布

问题:

I'm trying to arrange two ggplot object converted to a plotly object and use one common legend. But the legend is somehow doubled:

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)

I tried

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

but the whole legend just vanishes

回答1:

I wasn't able to fix the double legend with two separate plots, but you can combine the two data frames to make a single faceted plot. Regardless of the legend issue, using a single data frame with faceting seems like a more natural approach, given that the grouping variable is the same in each data frame. In the example below, I've removed the facet strips in order to match your example, but you can keep them by deleting the theme statement.

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)