如何创建scale_fill_manual()

时间:2016-08-26 12:11:02

标签: r ggplot2 customization geom-bar 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")

enter image description here

问题:我如何制作奥迪红色(&#34;红色&#34;)和福特蓝色(&#34;蓝调&#34;)的调色板,同时保留其他紫色(&#34; Purples&#34;)?

将这些红色/蓝色/紫色调色板放入变量并将其传递给scale_fill_manual()(如in this related Q&A所述)最方便(最好是整齐)的方法是什么?

1 个答案:

答案 0 :(得分:0)

完整的解决方案:

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() 

enter image description here