sch*_*sie 3 plot r ggplot2 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)
Run Code Online (Sandbox Code Playgroud)
我试过了
subplot(ggplotly(p1), ggplotly(p2), nrows = 1) %>% layout(showlegend = FALSE)
Run Code Online (Sandbox Code Playgroud)
但整个传说都消失了
我无法使用两个单独的图修复双重图例,但您可以将两个数据框组合成一个单面图.无论传说问题如何,考虑到每个数据框中的分组变量相同,使用具有分面的单个数据框似乎是更自然的方法.在下面的示例中,我删除了构面条以匹配您的示例,但您可以通过删除该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)
Run Code Online (Sandbox Code Playgroud)