install.packages("RColorBrewer")
library(RColorBrewer)
display.brewer.all()
这个包甚至可以提动专门为色盲提供的颜色表
display.brewer.all(colorblindFriendly = TRUE)
# 1. Visualize a single RColorBrewer palette
# by specifying its name
display.brewer.pal(n, name)
# 2. Return the hexadecimal color code of the palette
brewer.pal(n, name)
函数参数的描述: n:调色板中不同颜色的数量,最小值为3,最大值取决于调色板。 name:上面列表中的调色板名称。 例如name = RdBu。 以下R代码演示了如何显示一个单一的r颜色brewer调色板。
# View a single RColorBrewer palette by specifying its name
display.brewer.pal(n = 8, name = 'Dark2')
# Hexadecimal color specification
brewer.pal(n = 8, name = "Dark2")
[1] "#1B9E77" "#D95F02" "#7570B3" "#E7298A" "#66A61E" "#E6AB02" "#A6761D"## [8] "#666666"
library("ggplot2")
# Box plot: changing the fill color by Species
bp <- ggplot(iris, aes(Species, Sepal.Length)) +
geom_boxplot(aes(fill = Species)) +
theme_minimal() +
theme(legend.position = "top")
bp
# Scatter plot: changing points color by Species
sp <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point(aes(color = Species)) +
theme_minimal()+
theme(legend.position = "top")
sp
ggplot2中提供了两种色标功能,用于使用rcolorbrewer调色板: scale_fill_brewer()用于箱形图,条形图,小提琴图,点图等 scale_color_brewer()用于行和点
# Box plot
bp + scale_fill_brewer(palette = "Dark2")
# Scatter plot
sp + scale_color_brewer(palette = "Dark2")
image.png
在基础图中使用RColorBrewer调色板,brewer.pal()函数用于生成颜色矢量。
# Barplot using RColorBrewer
barplot(c(2,5,7), col = brewer.pal(n = 3, name = "RdBu"))