将图例与 ggplot 和 patchwork 合并

问题描述 投票:0回答:1

用代码

library(ggplot2)
library(patchwork)

dat.a <- data.frame(year=rep(2021:2024,times=2),group=rep(c("A","B"),each=4),val=runif(8,1,10))
dat.b <- data.frame(year=rep(2021:2024,times=1),group=rep(c("A"),each=4),val=runif(4,1,10))

ggp.a <- ggplot(dat.a,aes(x=year,y=val,fill=group))+
            geom_bar(stat="identity") +
            scale_fill_manual(values=c("A"="red","B"="blue"))

            
ggp.b <- ggplot(dat.b,aes(x=year,y=val,fill=group))+
            geom_bar(stat="identity") +
            scale_fill_manual(values=c("A"="red","B"="blue"))

(ggp.a + ggp.b) +
plot_layout(guides="collect") & 
theme(legend.position="bottom")

我有剧情

enter image description here

如何将图例合并,而不是并排放置?我期望只得到“组 ■ A ■ B”,而不是“组 ■ A ■ B 组 ■ A”。

r ggplot2 patchwork
1个回答
0
投票

patchwork
仅当图例相同时才会合并图例。为了在以下情况下实现这一目标:一张图仅显示您可以或必须相应设置
limits=
的部分类别。此外,在您的情况下,我们还必须将
show.legend=TRUE
添加到
geom
,对于
ggplot2 >= 3.5.0
来说,需要显示缺失类别的图例键:

library(ggplot2)
library(patchwork)

dat.a <- data.frame(year = rep(2021:2024, times = 2), group = rep(c("A", "B"), each = 4), val = runif(8, 1, 10))
dat.b <- data.frame(year = rep(2021:2024, times = 1), group = rep(c("A"), each = 4), val = runif(4, 1, 10))

ggp.a <- ggplot(dat.a, aes(x = year, y = val, fill = group)) +
  geom_col(show.legend = TRUE) +
  scale_fill_manual(
    values = c("A" = "red", "B" = "blue"),
    limits = c("A", "B")
  )


ggp.b <- ggplot(dat.b, aes(x = year, y = val, fill = group)) +
  geom_col(show.legend = TRUE) +
  scale_fill_manual(
    values = c("A" = "red", "B" = "blue"),
    limits = c("A", "B")
  )

(ggp.a + ggp.b) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")

© www.soinside.com 2019 - 2024. All rights reserved.