我正在尝试使用拼凑将多个图表放入一页中。我有单独的图表作为组 1 和组 2,每种情况下都有 2 个图例。 但是,当我使用拼凑将它们放在一起时,图例不会收集(见下文)。
data(mtcars)
mydata1<-mtcars %>% slice(1:16)
mydata2<-mtcars %>% slice(17:32)
library(ggplot2)
library(patchwork)
set.seed(42) ## for sake of reproducibility
P1<-ggplot()+
geom_point(data = mydata1, mapping = aes(x = cyl, y = mpg,
col = disp, size = hp))+
ggtitle('Group 1')
P2<-ggplot()+
geom_point(data = mydata2, mapping = aes(x = cyl, y = mpg,
col = disp, size = hp))+
ggtitle('Group 2')
P3 <- P1 + P2 +
plot_layout(guides='collect', ncol = 2)
P3
我期望合并图例,以便 disp 的图例将覆盖其数据的传播,而 hp 的图例将适用于组 1 和组 2,因为它们具有不同的范围,给出如下所示的内容:
对于要收集的指南,它们需要相同(相同的限制、中断等),因此在这种情况下,您需要确保颜色和大小限制覆盖各组数据的全部范围。
library(ggplot2)
library(patchwork)
P1<-ggplot()+
geom_point(data = mydata1, mapping = aes(x = cyl, y = mpg,
col = disp, size = hp))+
scale_color_continuous(limits = range(mtcars$disp)) +
scale_size_continuous(limits = range(mtcars$hp)) +
ggtitle('Group 1')
P2<-ggplot()+
geom_point(data = mydata2, mapping = aes(x = cyl, y = mpg,
col = disp, size = hp))+
scale_color_continuous(limits = range(mtcars$disp)) +
scale_size_continuous(limits = range(mtcars$hp)) +
ggtitle('Group 2')
P1 + P2 +
plot_layout(guides='collect', ncol = 2)