gpt4 book ai didi

r - 如何创建由 scale_fill_manual() 使用的自定义调色板

转载 作者:行者123 更新时间:2023-12-04 17:57:26 28 4
gpt4 key购买 nike

考虑以下制作带有紫色调色板的条形图的代码

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

问题:如何为奥迪红色(“红色”)和福特蓝色(“蓝色”)制作调色板,同时保持其他紫色(“紫色”)?

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

最佳答案

完整的工作解决方案:

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

关于r - 如何创建由 scale_fill_manual() 使用的自定义调色板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39166027/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com