R programming-Graphics

Introduction to generating graphics in R

Posted by Yingshan Li on March 8, 2020

Parameters in R plotting (function par() is used to define parameters in R plotting)

Choose the righ “type” in R plotting

  1. type= ”p “ Plot points in graphics
  2. type= ”l “  Plot lines in graphics
  3. type= ”b “  Plot points joined by lines
  4. type= ”o “  Plot overplotted points and lines
  5. type= ”h “  Plot histogram-like vertical lines
  6. type= ”s “  Plot stair steps
  7. type= ”n “  Does not produce any points or lines

a)符号和线条

  1. pch:制定绘制点是使用的符号,常见的0表示正方形,1表示圆圈,2表示三角形
  2. cex:制定符号大小,默认值为1,1.5表示放大1.5倍
  3. lty:指定线条类型,常见的1表示直线,2表示虚线
  4. lwd指定线条宽度
  5. type类型:
  6. 线型
  7. 只有点(空心点)
  8. 点(空心点)和线同时
  9. 点(实心点)和线同时

b)颜色

  1. col:要绘制的点和线的颜色,hsv()函数可以基于色相、饱和度、亮度来调色,rgb()函数可以基于红绿蓝三色值调色
  2. col.axis:坐标轴上刻度的颜色
  3. col.lab:坐标轴标签的颜色
  4. col.main:主标题的颜色
  5. col.sub:副标题的颜色
  6. fg:图形的前景色
  7. bg:图形的背景色

R中用来创建多个连续型颜色变量的函数:rainbow(n); heat.colors(n); terrain.colaors(); topo.colors(); cm.colors(). 另外最受欢迎的调色包RColorBrew, 其中最重要的函数就是brewer.pal(), 还有brewer.pal.info()可以输出所有颜色系,然后利用display.brewer.pal()函数可以输出颜色图形, eg:

library("RColorBrew")
n <- 10
mycolors <- brewer.pal(n, "Set1")
barplot(rep(1, n), col=mycolors)

c)文本字体属性

  1. font,值为整数,1=常规,2=粗体,3=斜体,4=粗斜体,5=符号字体
  2. font.axis 坐标轴刻度文字的字体
  3. fon.lab 坐标轴标签文字的字体
  4. font.main 主标题字体样式
  5. font.sub 副标题字体样式
  6. 字体的磅值,文本的最终大小为ps*cex

d)图形尺寸与边界尺寸

  1. pin(n1, n2) 图形尺寸,n1表示宽度,n2表示高度
  2. mai(n1, n2, n3, n4) 边界大小,分别是上下左右,单位为英寸
  3. mar(n1, n2, n3, n4) 边界大小,分别是上下左右,单位为英分

e)添加文本、自定义坐标轴与图例

  1. title()函数添加标题和坐标轴标签。main表示主标题,sub表示副标题,xlab表示横坐标轴标签,ylab表示纵坐标轴标签,xlim和ylim表示坐标轴范围
  2. axis()函数自定义坐标轴. side:表示在图形的哪一边绘制坐标轴,1=下;2=左,3=上,4=右 at:表示需要绘制哪一个变量的坐标轴 labels:刻度线下面的文字标签 lty:线条类型 col:线条和刻度线颜色 las:0表示标签平行于坐标抽,2表示标签垂直于坐标轴
  3. abline(h=yvalues, v=xvalues)函数添加参考线
  4. legend(location, title, legend, …)函数添加图例
  5. text(location, “text to place”, pos,…) 文本标注
  6. 图形的组合:par(mfrow=c(n,m))或者使用layout(matrix)函数,更精细的绘图需要用par(fig())图形参数