R绘图基础(2)颜色

计算机保存及还原颜色时有多种方案,较为常用的是两个,RGB和HSV。R预设了657种颜色,可以通过colors()函数调用(或者英式拼写colours())。比如我们常用的红,绿,蓝,

  1. > colors()[c(552,254,26)]
  2. [1] "red" "green" "blue"

我们可以使用grep来调取我们感兴趣的颜色,

  1. > grep("red",colors())
  2. [1] 100 372 373 374 375 376 476 503 504 505 506 507 524 525 526 527 528 552 553
  3. [20] 554 555 556 641 642 643 644 645
  4.  
  5. > colors()[grep("red",colors())]
  6. [1] "darkred" "indianred" "indianred1" "indianred2"
  7. [5] "indianred3" "indianred4" "mediumvioletred" "orangered"
  8. [9] "orangered1" "orangered2" "orangered3" "orangered4"
  9. [13] "palevioletred" "palevioletred1" "palevioletred2" "palevioletred3"
  10. [17] "palevioletred4" "red" "red1" "red2"
  11. [21] "red3" "red4" "violetred" "violetred1"
  12. [25] "violetred2" "violetred3" "violetred4"
  13.  
  14. > colors()[grep("sky",colors())]
  15. [1] "deepskyblue" "deepskyblue1" "deepskyblue2" "deepskyblue3"
  16. [5] "deepskyblue4" "lightskyblue" "lightskyblue1" "lightskyblue2"
  17. [9] "lightskyblue3" "lightskyblue4" "skyblue" "skyblue1"
  18. [13] "skyblue2" "skyblue3" "skyblue4"
  19.  
  20. > SetTextContrastColor <- function(color)
  21. + {
  22. + ifelse( mean(col2rgb(color)) > 127, "black", "white")
  23. + }
  24. > # Define this array of text contrast colors that correponds to each
  25. > # member of the colors() array.
  26. > TextContrastColor <- unlist( lapply(colors(), SetTextContrastColor) )
  27.  
  28. > # 1a. Plot matrix of R colors, in index order, 25 per row.
  29. > # This example plots each row of rectangles one at a time.
  30. > colCount <- 25 # number per row
  31. > rowCount <- 27
  32. > plot( c(1,colCount), c(0,rowCount), type="n", ylab="", xlab="",
  33. + axes=FALSE, ylim=c(rowCount,0))
  34. > title("R colors")
  35. >
  36. > for (j in 0:(rowCount-1))
  37. + {
  38. + base <- j*colCount
  39. + remaining <- length(colors()) - base
  40. + RowSize <- ifelse(remaining < colCount, remaining, colCount)
  41. + rect((1:RowSize)-0.5,j-0.5, (1:RowSize)+0.5,j+0.5,
  42. + border="black",
  43. + col=colors()[base + (1:RowSize)])
  44. + text((1:RowSize), j, paste(base + (1:RowSize)), cex=0.7,
  45. + col=TextContrastColor[base + (1:RowSize)])
  46. + }

R绘图基础(2)颜色-图片1

R颜色表

对于大多数理工出身的人来讲,理解颜色并不难,难的是如何选择一种或者多种理想的颜色,让绘图很漂亮。R当中有一个包RColorBrewer就可以为我们解决这个难题,其中预设了很多种颜色组合以供我们使用。

  1. > library(RColorBrewer)
  2. > display.brewer.all()

R绘图基础(2)颜色-图片2

RColorBrewer中预设的颜色表

我们看到其中Set3和Paired设定了12种颜色,其余的有多有少,以9种居多。在使用其颜色时,使用brewer.pal(n, name)调用即可,其中n最小值为3最大值为每组预设值数组的长度。比如brewer.pal(12,Paired)

在绘图时,有如下颜色参数

参数描述
col绘图使用的颜色,许多函数接受一组颜色,并对不同的数据依次使用颜色。
col.axis坐标轴字符颜色
col.labx,y坐标标记颜色
col.main标题颜色
col.sub副标题颜色
fg绘图前景色,包括坐标轴,各类boxes
bg绘图背景色
  1. > require(graphics)
  2. > par(col.axis="green",col.lab="blue",col.main="darkred",fg="white",bg="black")
  3. > plot(cars,main="speed vs dist")

R绘图基础(2)颜色-图片3

颜色设置示例

发表评论

匿名网友

拖动滑块以完成验证
加载失败