如何创建由scale_fill_manual()使用的自定义调色板 [英] How to create custom color palette to be used by scale_fill_manual()

查看:2647
本文介绍了如何创建由scale_fill_manual()使用的自定义调色板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码,它使用紫色调色板制作条形图

  library(dplyr)
library (ggplot2)

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

mm < - dd%>%
group_by(manufacturer)%>%
summary(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)



问题 >:如何使奥迪红色(红色)和福特蓝色(蓝色)的调色板保持紫色(Purples)?

将这些红色/蓝色/紫色调色板放入一个变量并传递给 scale_fill_manual()的最方便(最好是反色) (如


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

解决方案

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

这篇关于如何创建由scale_fill_manual()使用的自定义调色板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆