How to create custom color palette to be used by scale_fill_manual()

冷暖自知 提交于 2019-12-12 20:42:38

问题


Consider the following code that makes a bar chart with a purple color palette

library(dplyr)
library(ggplot2)

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

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

dd %>% left_join(mm) %>%
        ggplot(mapping = aes(x = reorder(manufacturer, mcyl), y = n, fill = factor(cyl))) + 
        geom_bar(stat = "identity", position = "fill") +
        coord_flip() +
        scale_fill_brewer(palette = "Purples")

Question: How can I make the palette for Audi red ("Reds") and for Ford blue ("Blues"), while keeping the others purple ("Purples")?

What is the most convenient (preferably tidyverse) way to put these red/blue/purple palettes in a variable and passing it to scale_fill_manual() (as explained in this related Q&A)?


回答1:


Full working solution:

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

# create palettes
library(RColorBrewer)
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)

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

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



来源:https://stackoverflow.com/questions/39166027/how-to-create-custom-color-palette-to-be-used-by-scale-fill-manual

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!