[英]Plotly subplot with two ggplots and common legend?
我正在嘗試將兩個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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.