RColorBrewer是一个R包,使用这个网站提供的颜色。我们画一个包括八个box的boxplot时,或者在x-y散点图上画六条线时,该怎样选择颜色呢?这个包就可以帮你。
=======哪些颜色系可以使用?=======让我们先看看RColorBrewer给我们提供了哪些颜色系。将如下代码写进test.R并运行。(运行方式:R CMD BATCH test.R)### Load the package or install if not presentif (!require("RColorBrewer")) { install.packages("RColorBrewer")library(RColorBrewer)}### Set the display a 1 by 1 gridpar(mfrow=c(1,1))### Show all the colour schemes availabledisplay.brewer.all()运行后生成的Rplots.pdf显示如下:共有三组颜色可供使用:- Sequential,按顺序渐变的。 - Light colours for low data, dark for high data
- Diverging,彼此之间差异变化较大的。 - Light colours for mid-range data, low and high contrasting dark colours
- Qualitative,这个用于最大程度地显示不同类之间的差别。 - Colours designed to give maximum visual difference between classes
=======如何使用RColorBrewer?=======
还是举例说明。运行如下代码。### Load the package or install if not presentif (!require("RColorBrewer")) { install.packages("RColorBrewer")library(RColorBrewer)}### Set the display a 1 by 1 gridpar(mfrow=c(1,1))### Generate random data matrixrand.data <- replicate(8,rnorm(100,100,sd=1.5))### Draw a box plot, with each box coloured by the 'Set3' paletteboxplot(rand.data,col=brewer.pal(8,"Set3"))结果如下:我们生成了8组随机数,然后作boxplot.col=brewer.pal(8,"Set3")表示使用Set3的8种颜色。=======其他画图函数中的使用=======除了boxplot,其他的画图函数中也能使用RColorBrewer。### Load the package or install if not presentif (!require("RColorBrewer")) { install.packages("RColorBrewer")library(RColorBrewer)}### Set the display a 2 by 1 gridpar(mfcol=c(2,1))### Generate random data matrixrand.data <- replicate(8,rnorm(100,100,sd=1.5))### Draw plot of counts coloured by the 'Set3' pallattebr.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 charttable.data <- table(round(rand.data))cols <- colorRampPalette(brewer.pal(8,"Dark2"))(length(table.data))pie(table.data,col=cols)结果如下:嗯,忽视这个饼图吧,有点儿丑……=======颜色不够用怎么办?=======使用colorRampPalette可以扩展颜色。if (!require("RColorBrewer")) { install.packages("RColorBrewer")library(RColorBrewer)}### Set the display a 1 by 1 gridpar(mfrow=c(1,1))newpalette<-colorRampPalette(brewer.pal(9,"Blues"))(10)### Generate random data matrixrand.data <- replicate(10,rnorm(100,100,sd=1.5))### Draw a box plot, with each box coloured by the 'newpalette' paletteboxplot(rand.data,col=newpalette)运行结果如下:colorRampPalette将Blues系列的第九个颜色进行了延伸,产生了10种渐变色。