使用多个调色板在条形图中创建自定义图例

Creating custom legend in bar chart with multiple color palettes

开始,我成功创建了一个包含多个调色板的条形图

问题:如何创建将 3 个调色板打印为 4x3 矩阵的自定义图例,至少包含行名称(柱面数),如下所示:

library(tidyr)

 purples %>% full_join(reds) %>% full_join(blues) %>% spread(manufacturer, colr)

# A tibble: 4 x 4
    cyl    audi    ford    <NA>
* <int>   <chr>   <chr>   <chr>
1     4 #FEE5D9 #EFF3FF #F2F0F7
2     5 #FCAE91 #BDD7E7 #CBC9E2
3     6 #FB6A4A #6BAED6 #9E9AC8
4     8 #CB181D #2171B5 #6A51A3

但随后用漂亮的图例颜色框替换了颜色代码。有点相关的是 this Q&A,但是图例在网格中,而不是在彼此之上。

完整的工作解决方案:

library(dplyr)
library(ggplot2)
library(gridExtra)
library(RColorBrewer)
library(tidyr)

cyl <- sort(unique(mpg$cyl))
ncat <- length(cyl)          # 4 types of cylinders

dd <- mpg %>% 
        group_by(manufacturer, cyl) %>% 
        summarise(n = n()) %>%
        ungroup() 

# create palettes
purples <- tibble(cyl, colr = brewer.pal(ncat, "Purples"))
reds    <- tibble(manufacturer = "audi", cyl, colr = brewer.pal(ncat, "Reds"))
blues   <- tibble(manufacturer = "ford", cyl, colr = brewer.pal(ncat, "Blues"))

# merge them with the data
dd_p <- dd %>% filter(!(manufacturer %in% c("audi", "ford"))) %>% left_join(purples)
dd_r <- dd %>% filter(manufacturer == "audi") %>% left_join(reds)
dd_b <- dd %>% filter(manufacturer == "ford") %>% left_join(blues)

mm <- dd %>%
        group_by(manufacturer) %>%
        summarise(mcyl = weighted.mean(cyl, n)) %>%
        arrange(mcyl) %>%
        ungroup()

gg_dd <- rbind(dd_p, dd_r, dd_b) %>%
        left_join(mm)

main_plot <- gg_dd %>% 
        ggplot(mapping = aes(x = reorder(manufacturer, mcyl), y = n, fill = colr)) + 
        geom_bar(stat = "identity", position = "fill") +
        coord_flip() +
        scale_fill_identity() 

combined_legend<- purples %>% 
        full_join(reds) %>% 
        full_join(blues) %>%
        mutate(manufacturer = ifelse(is.na(manufacturer), "generic", manufacturer)) %>% ggplot(mapping = aes(y = manufacturer, x = factor(cyl), fill = colr)) + 
        geom_tile() + 
        scale_fill_identity() + 
        coord_fixed()

grid.arrange(main_plot, combined_legend, heights=c(10,2), ncol=1)