如何创建供 scale_fill_manual() 使用的自定义调色板
How to create custom color palette to be used by scale_fill_manual()
考虑以下使用紫色调色板制作条形图的代码
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")
问题:如何为奥迪红色 ("Reds") 和福特蓝色 ("Blues") 制作调色板,同时保持其他紫色("Purples")?
将这些 red/blue/purple 调色板放入变量并将其传递给 scale_fill_manual()
(如 in this related Q&A 所述)的最方便(最好是 tidyverse)方法是什么?
完整的工作解决方案:
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()
考虑以下使用紫色调色板制作条形图的代码
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")
问题:如何为奥迪红色 ("Reds") 和福特蓝色 ("Blues") 制作调色板,同时保持其他紫色("Purples")?
将这些 red/blue/purple 调色板放入变量并将其传递给 scale_fill_manual()
(如 in this related Q&A 所述)的最方便(最好是 tidyverse)方法是什么?
完整的工作解决方案:
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()