【问题标题】:Plotly subplot with two ggplots and common legend?用两个 ggplots 和常见的图例来绘制子图?
【发布时间】:2016-11-02 20:52:13
【问题描述】:

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

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)

但整个传说都消失了

【问题讨论】:

    标签: r plot ggplot2 plotly


    【解决方案1】:

    我无法使用两个单独的图来修复双图例,但您可以将两个数据框组合成一个单面图。不管图例问题如何,考虑到每个数据框中的分组变量相同,使用带有分面的单个数据框似乎是一种更自然的方法。在下面的示例中,我删除了分面条以匹配您的示例,但您可以通过删除 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)
    

    【讨论】:

    • 感谢您的回答。当一个区域被选中时,你知道如何在两个图中选择相同的区域吗?
    • 您的意思是希望 x 轴和 y 轴的范围相同吗?如果是这样,则有多个选项。 (1) 删除scales="free"。 (2) 将facet_wrap(~ df, scales="free") + 替换为facet_grid(. ~ df) +。 (3) 手动设置范围,例如,scale_y_continuous(limits=c(-0.2,0.3)) 和 x 轴类似。 (4) 使用coord_cartesian(xlim=c(-0.3, 0.4), ylim=c(-0.2, 0.4))手动设置范围。
    • 谢谢。但我想要的是在 plotly 对象中:我可以通过绘制一个矩形或某个区域来放大。然后只有选定图上的轴会适应。但我希望两个轴都能适应。
    猜你喜欢
    • 2013-02-28
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多