绘制带有两个ggplots和通用图例的子图? [英] Plotly subplot with two ggplots and common legend?

查看:144
本文介绍了绘制带有两个ggplots和通用图例的子图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将两个ggplot对象转换为一个plotly对象,并使用一个常见的图例.但是传说以某种方式翻了一番:

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)

我尝试过

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

但是整个传说都消失了

推荐答案

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

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)

这篇关于绘制带有两个ggplots和通用图例的子图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆