首先我反正是才知道,怎么知道的呢?摸魚莫得~~
在 twitter 上摸魚看到這樣一條消息:
Did you know the latest version of ggplot2 allows you to set the default colour/fill scale functions via global options?

然后我就來到了這里:
Discrete colour scales
默認(rèn)配色
首先我們通過官方自帶的示例來看 ggplot2 默認(rèn)的配色是什么樣的?
library(ggplot2)
# 為了后面出圖顯得代碼不冗余,這里編寫了一個(gè)函數(shù)
cty_by_var <- function(var) {
ggplot(mpg, aes(cty, colour = factor({{var}}), fill = factor({{var}}))) +
geom_density(alpha = 0.2)
}
cty_by_var(class)

emm,可以看到,典型的 ggplot2 風(fēng)格。那么我們?cè)趺葱薷?ggplot2 默認(rèn)顏色搭配呢?
修改 ggplot2 默認(rèn)配色
這里不得不提到一個(gè)參數(shù) ggplot2.discrete.fill = ... ,顧名思義,離散型顏色填充。
# 指定顏色集(一個(gè)對(duì)色盲用戶者比較友好的配色)
okabe <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
# 通過with_options() 函數(shù)局部改變 ggplot2 配色,如果需要全局改變,那么就用 `options()` 函數(shù)
withr::with_options(
list(ggplot2.discrete.fill = okabe),
print(cty_by_var(class))
)

這個(gè)時(shí)候來看這個(gè)圖的顏色,是不是變了?而且比較順眼一些了。
根據(jù) levels 數(shù)目來自動(dòng)匹配配色方案
discrete_palettes <- list(
c("skyblue", "orange"),
RColorBrewer::brewer.pal(3, "Set2"),
RColorBrewer::brewer.pal(6, "Accent")
)
> discrete_palettes
[[1]]
[1] "skyblue" "orange"
[[2]]
[1] "#66C2A5" "#FC8D62" "#8DA0CB"
[[3]]
[1] "#7FC97F" "#BEAED4" "#FDC086" "#FFFF99" "#386CB0" "#F0027F"
然后可以將以上顏色集列表一一對(duì)應(yīng)不同的圖的默認(rèn)顏色
withr::with_options(
list(ggplot2.discrete.fill = discrete_palettes), {
# 1st palette is used when there 1-2 levels (e.g., year)
# 當(dāng)只有 1-2 個(gè) levels 時(shí)候采用第一種配色方案
print(cty_by_var(year))
# 當(dāng)有 3 個(gè) levels 時(shí)候采用第二種配色
# 2nd palette is used when there are 3 levels
print(cty_by_var(drv))
# 當(dāng)有 4-6 個(gè) levels 時(shí)候采用第三種配色方案
# 3rd palette is used when there are 4-6 levels
print(cty_by_var(fl))
})
也可以分開寫
- 1-2 個(gè) levels 時(shí)候(這里兩個(gè))
withr::with_options(
list(ggplot2.discrete.fill = discrete_palettes), {
print(cty_by_var(year))
})

- 三個(gè) levels 時(shí)候
withr::with_options(
list(ggplot2.discrete.fill = discrete_palettes), {
print(cty_by_var(drv))
})

- 4-6 個(gè) levels 時(shí)候(這里五個(gè))
withr::with_options(
list(ggplot2.discrete.fill = discrete_palettes), {
print(cty_by_var(fl))
})

小結(jié)
我覺得這種針對(duì)于不用 levels 數(shù)目,提供不同的配色配色方案,對(duì)于我們?cè)诰帉懣梢暬瘮?shù)配色方面還是很方便的。
不過往往我們?cè)诎l(fā)表文章的時(shí)候,更多的時(shí)候還是按照同一個(gè)樣品或者變量在通篇文章中采用一個(gè)配色,所以我一般經(jīng)常使用的配色方案是通過 scale_fill_manual() 或者 scale_color_manual() 中的 values 參數(shù)來實(shí)現(xiàn),舉個(gè)例子,有變量 var_A、var_B、var_C,我就會(huì)這樣實(shí)現(xiàn):
scale_fill_manual(values = c(var_A = "red", var_B = "grey", var_C = "blue"))
or
scale_color_manual(values = c(var_A = "red", var_B = "grey", var_C = "blue"))