R语言之RColorBrewer的使用

25次阅读
没有评论

共计 2379 个字符,预计需要花费 6 分钟才能阅读完成。

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 显示如下:
R 语言之 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″))
结果如下:
R 语言之 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)
结果如下:
R 语言之 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)

运行结果如下:
R 语言之 RColorBrewer 的使用


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

正文完
 0