ggplot2中的配色方案(四)

ggplot2
色彩搭配
Author

Lee

Published

October 9, 2023

在科研作图中,配色是一个永远不变的关键,一个简洁、大方、美观的配色方案会让图形增色不少。

在R中,常用的配色包有两个,分别是RColorBrewerggsci,它们都可以和ggplot2连用,绘制出配色完美的图形。

1 RColorBrewer

1.1 查看RColorBrewer中的所有配色方案

library(RColorBrewer)
display.brewer.all(type = "all")
图 1: RColorBrewer包中所有的配色方案

可以看出,RColorBrewer包中的配色方案主要有三种:

  • 离散型颜色(离散型)
  • 单种颜色渐变色(连续型)
  • 两种颜色渐变色(连续型)

1.2 选取其中一个配色方案进行具体展示

可以通过brewer.pal()函数获取指定配色方案的16进制颜色编码,这样我们就可以在之后的绘图中手动挑选自己喜欢的颜色了。

tempColors <- brewer.pal(9, "BuGn") # 获取配色方案的十六进制代码
scales::show_col(tempColors, labels = T)

1.3 在ggplot2中使用选取的配色方案

1.3.1 离散型配色

ggplot2中使用RColorBrewer中的配色方案需要使用scale_fill_brewer()scale_color_brewer()

library(tidyverse)
library(RColorBrewer)

p <- subset(diamonds, carat >= 2.2) |>
  ggplot(aes(x = table, y = price, color = cut)) +
  geom_point(alpha = 0.7) +
  geom_smooth(method = "loess", alpha = 0.5, linewidth = 1, span = 1) +
  theme_bw()

p

p + scale_color_brewer(palette = "Set1")

1.3.2 连续型配色

ggplot2中使用RColorBrewer中的配色方案需要使用scale_**_distiller()函数。

data <- data.frame(
  x = 1:10,
  y = 1:10,
  z = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
)

ggplot(data, aes(x = x, y = y, color = z)) +
  geom_point(size = 5) +
  scale_color_distiller(palette = "Spectral")

2 ggsci

包如其名,收录了若干知名的颜色方案。与RColorBrewer不同,ggsci中直接使用scale_**_配色名称()函数调用相关配色。

library(ggsci)
p <- subset(diamonds, carat >= 2.2) |>
  ggplot(aes(x = table, y = price, color = cut)) +
  geom_point(alpha = 0.7) +
  geom_smooth(method = "loess", alpha = 0.5, linewidth = 1, span = 1) +
  theme_bw()

p

3 学习使用

  1. 使用vignette("ggsci")函数查看各种配色方案及其使用的说明。
  2. 使用pal_配色方案名() 获取配色方案16进制颜色编码。
  3. 使用scale_color_配色方案名()在ggplot中应用选择的配色方案。
  4. 使用scale_*_manual()scale_*_gradient()自定义配色,前者自定义离散型,后者自定义连续型。
vignette("ggsci") # 查看各种配色方案的使用说明

pal_npg("nrc")(10) # 获取16进制颜色编码
 [1] "#E64B35FF" "#4DBBD5FF" "#00A087FF" "#3C5488FF" "#F39B7FFF" "#8491B4FF"
 [7] "#91D1C2FF" "#DC0000FF" "#7E6148FF" "#B09C85FF"
scales::show_col(pal_npg("nrc")(10)) # 将颜色编码转化为颜色

library(ggplot2)
# 自定义离散型变量颜色
data <- data.frame(
  x = 1:5,
  y = 1:5,
  category = c("A", "B", "C", "D", "E")
)
ggplot(data, aes(x = x, y = y, color = category)) +
  geom_point(size = 5) +
  scale_color_manual(
    values = c(
      "A" = "red",
      "B" = "blue",
      "C" = "green",
      "D" = "orange",
      "E" = "purple"
    )
  )

# 自定义连续型变量颜色
library(ggplot2)
library(RColorBrewer)
data <- data.frame(
  x = 1:10,
  y = 1:10,
  z = 1:10
)
ggplot(data, aes(x = x, y = y, fill = z)) +
  geom_tile() +
  scale_fill_gradientn(colors = brewer.pal(3, "Blues")) # 创建多个颜色梯度。