RColorBrewer的使用

RColorBrewer是一个R包,使用http://colorbrewer2.org/这个网站提供的颜色。我们画一个包括八个box的boxplot时,或者在x-y散点图上画六条线时,该怎样选择颜色呢?这个包就可以帮你。

=======哪些颜色系可以使用?=======
让我们先看看
RColorBrewer给我们提供了哪些颜色系。
将如下代码写进test.R并运行。(运行方式:R CMD BATCH test.R)
### Load the package or install if not present
if (!require("RColorBrewer")) {
install.packages("RColorBrewer")
library(RColorBrewer)
}

### Set the display a 1 by 1 grid
par(mfrow=c(1,1))

### Show all the colour schemes available
display.brewer.all()

运行后生成的Rplots.pdf显示如下:
RColorBrewer的使用

共有三组颜色可供使用:

  1. Sequential,按顺序渐变的。 - Light colours for low data, dark for high data
  2. Diverging,彼此之间差异变化较大的。 -  Light colours for mid-range data, low and high contrasting dark colours
  3. Qualitative,这个用于最大程度地显示不同类之间的差别。 - Colours designed to give maximum visual difference between classes

=======如何使用RColorBrewer?=======
还是举例说明。运行如下代码。
### Load the package or install if not present
if (!require("RColorBrewer")) {
install.packages("RColorBrewer")
library(RColorBrewer)
}

### Set the display a 1 by 1 grid
par(mfrow=c(1,1))

### Generate random data matrix
rand.data <- replicate(8,rnorm(100,100,sd=1.5))

### Draw a box plot, with each box coloured by the 'Set3' palette
boxplot(rand.data,col=brewer.pal(8,"Set3"))
结果如下:
RColorBrewer的使用

我们生成了8组随机数,然后作boxplot.
col=brewer.pal(8,"Set3")表示使用Set3的8种颜色。

=======其他画图函数中的使用=======

除了boxplot,其他的画图函数中也能使用RColorBrewer。
### Load the package or install if not present
if (!require("RColorBrewer")) {
install.packages("RColorBrewer")
library(RColorBrewer)
}

### Set the display a 2 by 1 grid
par(mfcol=c(2,1))

### Generate random data matrix
rand.data <- replicate(8,rnorm(100,100,sd=1.5))

### Draw plot of counts coloured by the 'Set3' pallatte
br.range <- seq(min(rand.data),max(rand.data),length.out=10)
results <- sapply(1:ncol(rand.data),function(x) hist(rand.data[,x],plot=F,br=br.range)$counts)
plot(x=br.range,ylim=range(results),type="n",ylab="Counts")
cols <- brewer.pal(8,"Set3")
lapply(1:ncol(results),function(x) lines(results[,x],col=cols[x],lwd=3))

### Draw a pie chart
table.data <- table(round(rand.data))
cols <- colorRampPalette(brewer.pal(8,"Dark2"))(length(table.data))
pie(table.data,col=cols)
结果如下:
RColorBrewer的使用

嗯,忽视这个饼图吧,有点儿丑……

=======颜色不够用怎么办?=======
使用colorRampPalette可以扩展颜色。
if (!require("RColorBrewer")) {
install.packages("RColorBrewer")
library(RColorBrewer)
}

### Set the display a 1 by 1 grid
par(mfrow=c(1,1))

newpalette<-colorRampPalette(brewer.pal(9,"Blues"))(10)

### Generate random data matrix
rand.data <- replicate(10,rnorm(100,100,sd=1.5))

### Draw a box plot, with each box coloured by the 'newpalette' palette
boxplot(rand.data,col=newpalette)

运行结果如下:
RColorBrewer的使用

colorRampPalette将Blues系列的第九个颜色进行了延伸,产生了10种渐变色。

---------------------------------------------------------------------------------- 数据和特征决定了效果上限,模型和算法决定了逼近这个上限的程度 ----------------------------------------------------------------------------------
原文地址:https://www.cnblogs.com/payton/p/4806811.html