R语言 为具有通用因子的独特组合的多个ggplot创建一个通用图例

lymgl2op  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(87)

我有几个条形图与一个普遍因素的独特水平组合。我想在所有图之间实现共享图例,显示因子的所有水平。

library(ggplot2)
library(grid)
library(gridExtra)

set.seed(1)
df1 <- data.frame(c=c('a', 'b', 'c', 'd', 'e'), x=1:5,  y=runif(5))
df2 <- data.frame(c=c('a', 'c', 'e', 'f', 'g'), x=1:5,  y=runif(5))

dd <- union(df1$c,df2$c) #### combine all factor levels into one string
dd.col <- rainbow(length(dd)) ### some colors, could be anything
names(dd.col)  <- dd #### create a named vector of all factors present in all unified plots

g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + 
  geom_bar(stat="identity") +
  scale_fill_manual("Legend", values = dd.col)
g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + 
  geom_bar(stat="identity") +
  scale_fill_manual("Legend", values = dd.col)
grid.arrange(g1, g2, ncol=2)

这里有一个解决方案,它可以产生所需的输出,但它很笨拙,对我的数据集(许多图,许多水平)不太实用。

df3 <- data.frame(c=c('a', 'b', 'c', 'd', 'e', 'f', 'g'), x=1:7,  y=runif(7))
g3 <- ggplot(df3, aes(x=x, y=y, fill=c)) + 
  geom_bar(stat="identity") +
  scale_fill_manual("Legend", values = dd.col) +
  theme(legend.position = "bottom")

library(cowplot)

leg <- get_legend(g3)
plot_grid(
  plot_grid(g1 + theme(legend.position = "none"),
            g2 + theme(legend.position = "none"), ncol=2),
          leg,
          align = "hv", nrow=2, rel_heights = c(1,0.1))

对于具有多个分组因子水平的大型数据集,什么是更好的解决方案?

f45qwnt8

f45qwnt81#

若要在两个图例中显示所有类别,请设置尺度的limits以包括因子的所有水平。最后,为了得到一个共享的图例,你可以使用patchwork

library(ggplot2)
library(patchwork)

g1 <- ggplot(df1, aes(x = x, y = y, fill = c)) +
  geom_bar(stat = "identity") +
  scale_fill_manual("Legend", values = dd.col, limits = dd)

g2 <- ggplot(df2, aes(x = x, y = y, fill = c)) +
  geom_bar(stat = "identity") +
  scale_fill_manual("Legend", values = dd.col, limits = dd)

g1 + g2 + 
  plot_layout(guides = "collect")

相关问题