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

时间:2016-08-26 18:53:59

标签: r ggplot2 bar-chart legend geom-bar

Picture开始,我设法创建了一个带有多个调色板的条形图

this other Q&A

问题:如何创建一个自定义图例,将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

然后将颜色代码替换为漂亮的图例颜色框。有些相关的是enter image description here,但随后是网格中的图例,而不是彼此之上。

1 个答案:

答案 0 :(得分:1)

完整的解决方案:

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)

enter image description here