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種漸變色。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM