Basic

Barplot

参数 描述
x,y bottom,bottomleft,left,topleft,top,topright,right,bottomright,center
inset 设置在主绘图边距
title 图例的标题
legend 图例的内容
attach(diamonds)
par(mfrow = c(1, 2))
d <- table(clarity, cut)
barplot(d, main = "Diamonds Distribution by clarity and cut", xlab = "Clarity", 
        legend = rownames(d), horiz = TRUE,
        col=c("#4285F4", "#34A853","#FFBB00","#EA4335","#00A1F1"))
barplot(d, main = "Diamonds Diamondsby clarity and cut", xlab = "Clarity", beside = TRUE,
        col = terrain.colors(8))
legend("topleft", inset=.05, title="Cut",rownames(d),fill=terrain.colors(8), horiz=F)
detach(diamonds)

Layouts

R绘图所占的区域,被分成两大部分,一是外围边距,一是绘图区域。

外围边距可使用par()函数中的oma来进行设置。比如oma=c(4,3,2,1),就是指外围边距分别为下边距:4行,左边距3行,上边距2行,右边距1行.

绘图边距可以使用par()函数中mar来设置。比如mar=c(4,3,2,1),与外围边距的设置类似,是指绘图边距分别为下边距:4行,左边距3行,上边距2行,右边距1行.也可以使用mai来设置。mai与mar唯一不同之处在于mai不是以行为单位,而是以inch为单位。

绘图区域可使用par()函数中的mfrow,mfcol来进行布局。mfrow和mfcol可以使用绘图区域被区分为多个区域。默认值为mfrow(1,1)。

比如mfrow(2,3)就是指将绘图区域分成2行3列,并按行的顺序依次绘图填充; ,比如mfcol(3,2)就是指将绘图区域分成3行2列,并按列的顺序依次绘图填充;

SOUTH<-1; WEST<-2; NORTH<-3; EAST<-4
GenericFigure <- function(ID, size1, size2)
{
  plot(0:10, 0:10, type="n", xlab="X", ylab="Y")
  text(5,5, ID, col="red", cex=size1)  # red cex size ID
  mtext(paste0("cex ",size2), SOUTH, line=3, adj=1.0, cex=size2, col="blue") # maegintext
  box("plot", col="red") # red plot outline
  box("figure", lty="dotted", col="blue") # blue figure outline
  title(paste0("title",ID))
}
MultipleFigures <- function(n,direc)
{
  # mutpile figures fill by row
  # oma: outer margin area
  par(mfrow=c(2,2),mar=c(6,4,2,1),oma=c(8,3,2,1)) 
  GenericFigure("1", 3, 0.5)
  GenericFigure("2", 3, 1)
  GenericFigure("3", 3, 1.5)
  GenericFigure("4", 3, 2)
  box("inner", lty="dotted", col="yellow")
  box("outer", lty="solid", col="green")
  for(i in 0:n){
    mtext(paste("line",i,sep=""), direc, line=i, cex=1, col="black", adj=1, outer=TRUE)
  }
}

MultipleFigures(4,SOUTH) 

layout(mat, widths = rep(1, ncol(mat)), heights = rep(1,nrow(mat)),respect = FALSE)

attach(mtcars)
layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE))
hist(wt);hist(mpg);hist(disp)

layout(matrix(c(1,1,1,1,2,2,2,3,2,2,2,3),3,4,byrow=TRUE))
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    1    1
# [2,]    2    2    2    3
# [3,]    2    2    2    3
hist(wt);hist(mpg);hist(disp)

layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE),widths=c(3,1), heights=c(1,2))
hist(wt);hist(mpg);hist(disp)

layout(matrix(c(1,1,2,1,1,1),nrow=2,ncol=3,byrow=T))
hist(wt);hist(mpg)

Symbols(pch)

pch means plotting ‘character’:

Note that with bitmap output: -1. the filled symbols 15-18 may render without proper anti-aliasing; they can appear jagged, pixelated, and not properly centered, though this varies among platforms. -2. Symbols 19 and 21-25 have an outline around the filled area, and will render with smoothed edges on most platforms. -3. For symbols 21-25 to appear solid, you will also need to specify a fill (bg) color that is the same as the outline color (col); otherwise they will be hollow.

And square,circle,rectangle,lozenge(0,1,2,5/15,16,17,18/22,21,24,23) are commonly used in R.

pchShow <-
     function(extras = c("*",".", "o","O","0","+","-","|","%","#"),
              cex = 3, ## good for both .Device=="postscript" and "x11"
              col = "red3", bg = "gold", coltext = "blue", cextext = 1.2,
              main = paste("symbols:points(..., pch = *, cex =",cex,")"))
       {
           par(mar=c(2,1,2,1))  
           np  <- 26 + length(extras)
           ipch <- 0:(np-1)
           k <- floor(sqrt(np))
           rx <- c(-1,1)/2 + range(ix <- ipch %/% k)
           ry <- c(-1,1)/2 + range(iy <- ipch %% k)
           pch <- as.list(ipch) # list with integers & strings
           pch[26 + 1:length(extras)] <- as.list(extras)
           plot(rx, ry, type="n", axes = F, xlab = "", ylab = "",main = main)
           abline(v = ix, h = iy, col = "lightgray", lty = "dotted")
           for(i in 1:np) {
               points(ix[i], iy[i], pch = pch[[i]], 
                      col = col, bg = bg, cex = cex)
               if(cextext > 0)
                     text(ix[i] - 0.3, iy[i], pch[[i]],
                          col = coltext, cex = cextext)
             }
        }
pchShow()

Linetypes

lty: line type. lwd: line width

Linetype: 0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash

par(mar=c(0,0,0,0))

## Set up the plotting area
plot(NA, xlim=c(0,1), ylim=c(-0.5,6.5),
         xaxt="n", yaxt="n",
         xlab=NA, ylab=NA)

## Draw the lines
for (i in 0:6) {
    points(c(0.25,1), c(i,i), lty=i, lwd=2.5, type="l")
}
## Add labels
text(0, 0, "0. 'blank'"   ,  adj=c(0,.5))
text(0, 1, "1. 'solid'"   ,  adj=c(0,.5))
text(0, 2, "2. 'dashed'"  ,  adj=c(0,.5))
text(0, 3, "3. 'dotted'"  ,  adj=c(0,.5))
text(0, 4, "4. 'dotdash'" ,  adj=c(0,.5))
text(0, 5, "5. 'longdash'",  adj=c(0,.5))
text(0, 6, "6. 'twodash'" ,  adj=c(0,.5))

Only lines + type

 x <- 1:5
 y <- x + 5
 par(mfrow = c(2, 4),pch = 22)
 opts <- c("p", "l", "o", "b", "c", "s", "S", "h")
 for (i in 1:length(opts)) {
     plot(x, y, main = paste0("type=", opts[i]),type = "n")
     lines(x, y, type = opts[i],col="red")
 }

Axis

axis

参数 描述
main 主标题
sub 副标题
xlab x轴标记
ylab y轴标记
xlim x轴上下限(范围)
ylim y轴上下限
mgp 坐标轴标记,坐标字符,坐标刻度线距离坐标轴的行数,默认值为c(3,1,0)

增加一个新的坐标轴使用axis()函数。

参数 描述
side 坐标轴所在的位置,1:下,2:左,3:上,4:右
labels 坐标字符串
pos 坐标轴线所在的行,默认值为重绘所在位置上的原坐标
lty 线型
col 颜色
las 坐标标记与坐标轴方位关系,=0为平等,=2为垂直
cex.axis 坐标字符大小
tck 坐标轴标记长度及方向
lwd.ticks 坐标刻度线宽度
col.ticks 坐标刻度线颜色
(…) 其它par()中可用的参数
## A Silly Axis Example

## specify the data 
x <- 1:10 -> y; z <- 10/x
## create extra margin room on the right for an axis 
par(mar=c(5, 4, 4, 8))
## plot x vs. y 
plot(x, y, type="b", pch=21, col="red", bg="yellow", yaxt="n", lty=3, xlab="", ylab="")
## add x vs. 1/x 
lines(x, z, type="b", pch=22, col="blue", bg="red", lty=2)
## draw an axis on the left 
axis(2, at=x, labels=x, col.axis="red", las=2,
     lwd.ticks=2.5,col.ticks = "green")
## draw an axis on the right, with smaller text and ticks 
axis(4, at=z, labels=round(z), las=0, lty=3,
     cex.axis=1.5, tck=-.05)
## add a title for the right axis 
mtext("Y=1/X", side=4, line=3, cex.lab=1,las=2, col="black")
## add a main title and bottom and left axis labels 
title("An Example of Creative Axes", xlab="X values",ylab="Y=X")

mtext

文本框使用text或者mtext函数。 text可以在主绘图区内加文本框,mtext在边距或者外边距上加文本框。

text(location, “text to place”, pos, …) mtext(“text to place”, side, line=n, …)

参数 描述
location 图例所在位置
pos 所在的相对位置,1:下面,2:左边,3:上面,4:右边
side 所在边距的位置,1:下,2:左,3:上,4:右
cex.lab 坐标标记大小
cex.axis 坐标字符大小
其它par()可用的参数
attach(mtcars)
plot(wt, mpg, main="Milage vs. Car Weight", xlab="Weight", ylab="Mileage", pch=18, col="blue")
text(wt, mpg, row.names(mtcars), cex=0.6, pos=4, col="red")

Shapes

  • 点:points
  • 线:abline,lines,segments
  • 面:box,polygon,polypath,rect,circle
  • 特殊的:arrows,symbols

points

Use the pch option to set the shape, and use lty and lwd to set the line type and width. The line type can be specified by name or by number.

set.seed(1)

## Plot some points with lines
## Set up the plotting area
par(mar=c(2,3,2,3))
plot(NA, xlim=c(1,4), ylim=c(0,1))

## Plot solid circles with solid lines
points(1:4, runif(4), type="p", pch=19)
## Add open squares with dashed line, with heavier line width
points(1:4, runif(4), type="b", pch=0,  lty=2, lwd=3)

points(1:4, runif(4), type="b", pch=23,   ## Diamond shape
       lty="dotted", cex=2,               ## Dotted line, double-size shapes
       col="#000099", bg="#FF6666")       ## blue line, red fill

abline

abline可以由斜率和截距来确定一条直线,lines可以连接两个或者多个点,segments可以按起止位置画线

plot(1:10,(1:10)*2 + 1)
abline(h=6, v=8, col = "gray60")
text(8,6, "abline( h = 6 )", col = "gray60", adj = c(0, -.1))
abline(h = 4:8, v = 6:12, col = "lightgray", lty=3)
abline(a=1, b=2, col = 2)
text(5,11, "abline( 1, 2 )", col=4, adj=c(-.5,.5))
segments(6,4,9,5,col="green")

sale5 <- c(6, 4, 9, 7, 6, 12, 8, 10, 9, 13)
plot(sale5,new=T)
abline(lsfit(1:10,sale5))
abline(lsfit(1:10,sale5, intercept = FALSE), col= 4)
text(6,5,"segments(6,4,9,5)")
lines(sale5,col="pink")

attach(mtcars)
plot(wt, mpg, main="Scatterplot Example", xlab="Car Weight ", ylab="Miles Per Gallon ", pch=19)
# Add fit lines
abline(lm(mpg~wt), col="red") # regression line (y~x) 
lines(lowess(wt,mpg), col="blue") # lowess line (x,y)

detach(mtcars)
x <- -9:9
plot(x, sqrt(abs(x)),  col = "red")
lines(spline(x, sqrt(abs(x)), n=101), col = "green")

Circles

## Note that  example(trees)  shows more sensible plots!
N <- nrow(trees)
with(trees, {
    ## Girth is diameter in inches
      op <- palette(rainbow(N, end = 0.9))
      symbols(Height, Volume, circles = Girth/16, inches = FALSE, bg = 1:N, fg = "gray30", main = "symbols(*, circles = Girth/16, bg = 1:N)")
      palette(op)
       })

polygon

box画出当前盒子的边界,polygon画多边形,polypath画路径,rect画距形

set.seed(2018)
x <- c(1:20)
y <- sample(-20:20,20,replace = T)
op <- par(mfcol=c(3,1))
for(xpd in c(FALSE,TRUE,NA)) {
  plot(1:10, type="n",main = paste("xpd =", xpd))
  box("figure", col = "pink", lwd=3)
  polygon(x,y, xpd=xpd, col="orange", lty=2, lwd=2, border="red")
}

polypath

plotPath <- function(x, y, col = "grey", rule = "winding") {
  plot.new()
  plot.window(range(x, na.rm = TRUE), range(y, na.rm = TRUE))
  polypath(x, y, col = col, rule = rule)
  if (!is.na(col))
    mtext(paste("Rule:", rule), side = 1, line = 1)
}

plotRules <- function(x, y, title="") {
  plotPath(x, y)
  plotPath(x, y, rule = "evenodd")
  mtext(title, side = 3, line = 0)
  plotPath(x, y, col = NA)
}

op <- par(mfrow = c(5, 3), mar = c(2, 1, 1, 1))

plotRules(c(.1, .1, .9, .9, NA, .2, .2, .8, .8),
            c(.1, .9, .9, .1, NA, .2, .8, .8, .2),
            "Nested rectangles, both clockwise")
plotRules(c(.1, .1, .9, .9, NA, .2, .8, .8, .2),
            c(.1, .9, .9, .1, NA, .2, .2, .8, .8),
            "Nested rectangles, outer clockwise, inner anti-clockwise")
plotRules(c(.1, .1, .4, .4, NA, .6, .9, .9, .6),
            c(.1, .4, .4, .1, NA, .6, .6, .9, .9),
            "Disjoint rectangles")
plotRules(c(.1, .1, .6, .6, NA, .4, .4, .9, .9),
            c(.1, .6, .6, .1, NA, .4, .9, .9, .4),
            "Overlapping rectangles, both clockwise")
plotRules(c(.1, .1, .6, .6, NA, .4, .9, .9, .4),
            c(.1, .6, .6, .1, NA, .4, .4, .9, .9),
            "Overlapping rectangles, one clockwise, other anti-clockwise")

par(op)

Color

head(colors())
# [1] "white"         "aliceblue"     "antiquewhite"  "antiquewhite1"
# [5] "antiquewhite2" "antiquewhite3"
colors()[c(552,254,26)]
# "red"   "green" "blue" 
colors()[grep("sky",colors())]
#  [1] "deepskyblue"   "deepskyblue1"  "deepskyblue2"  "deepskyblue3"  "deepskyblue4" 
#  [6] "lightskyblue"  "lightskyblue1" "lightskyblue2" "lightskyblue3" "lightskyblue4"
# [11] "skyblue"       "skyblue1"      "skyblue2"      "skyblue3"      "skyblue4" 
col2rgb("peachpuff")
#       [,1]
# red    255
# green  218
# blue   185
col2rgb(c(blu = "royalblue", reddish = "tomato"))
#       blu reddish
# red    65     255
# green 105      99
# blue  225      71
col2rgb(paste0("gold", 1:4))
#       [,1] [,2] [,3] [,4]
# red    255  238  205  139
# green  215  201  173  117
# blue     0    0    0    0
SetTextContrastColor <- function(color)
{
   ifelse( mean(col2rgb(color))>127, "black", "white")
 }
## Define this array of text contrast colors that correponds to each
## member of the colors() array.
TextContrastColor <- unlist( lapply(colors(), SetTextContrastColor) )

## Plot matrix of R colors, in index order, 25 per row.
## This example plots each row of rectangles one at a time.
colCount <- 25
rowCount <- 27
plot( c(1,colCount), c(0,rowCount), type="n", xlab="", ylab="",
       axes=FALSE, ylim=c(rowCount,0))
title("R colors")
 
for (j in 0:(rowCount-1))
 {
     base <- j*colCount
     remaining <- length(colors()) - base
     RowSize <- ifelse(remaining < colCount, remaining, colCount)
     rect((1:RowSize)-0.5,j-0.5, (1:RowSize)+0.5,j+0.5,
                border="black",col=colors()[base+(1:RowSize)])
     text((1:RowSize), j, paste(base+(1:RowSize)), cex=0.7,
                col=TextContrastColor[base+(1:RowSize)])
}

参数 描述
col 绘图使用的颜色
col.axis 坐标轴字符颜色
col.lab x,y坐标标记颜色
col.main 标题颜色
col.sub 副标题颜色
fg 绘图前景色,包括坐标轴,各类boxes
bg 绘图背景色
par(col.axis="green",col.lab="blue",col.main="yellow",col.sub = "white",col = "purple",fg="white",bg="black")
plot(cars,main="speed vs dist",sub="subtitle")

Fonts

参数 描述
font 字体描述,1 正常,2 加粗,3 斜体,4 加粗,斜体,5 符号
font.axis 坐标轴字符描述
font.lab 坐标轴标记字体描述
font.main 标题字体描述
font.sub 副标题字体描述
ps 字体点阵大小,大约为1/72英寸。在使用时text size=ps*cex
cex 字体放大或者缩小多少倍
cex.axis 坐标轴字符大小
cex.lab 坐标轴标记字体大小
cex.main 标题字体大小
cex.sub 副标题字体大小
family 绘图字体。标准字体是“serif”,“sans”,“mono”,“symbol”。当然可以指定任何自己已有的字体库。但它是设备依赖的。
names(pdfFonts())
##  [1] "serif"                "sans"                 "mono"                
##  [4] "AvantGarde"           "Bookman"              "Courier"             
##  [7] "Helvetica"            "Helvetica-Narrow"     "NewCenturySchoolbook"
## [10] "Palatino"             "Times"                "URWGothic"           
## [13] "URWBookman"           "NimbusMon"            "NimbusSan"           
## [16] "URWHelvetica"         "NimbusSanCond"        "CenturySch"          
## [19] "URWPalladio"          "NimbusRom"            "URWTimes"            
## [22] "ArialMT"              "Japan1"               "Japan1HeiMin"        
## [25] "Japan1GothicBBB"      "Japan1Ryumin"         "Korea1"              
## [28] "Korea1deb"            "CNS1"                 "GB1"
## Try this in various font families (including Hershey)
## and locales.  Use sign=-1 asserts we want Latin-1.
## Standard cases in a MBCS locale will not plot the top half.
par(mfcol=c(1,3),mar=c(1,2,1,2))
TestChars <- function(sign=1, font=1, ...)
    {
          if(font == 5) { sign <- 1; r <- c(32:126, 160:254)
          } 
          else if (l10n_info()$MBCS) r <- 32:126 else r <- 32:255
          if (sign == -1) r <- c(32:126, 160:255)
          par(pty="s")
          plot(c(-1,16), c(-1,16), type="n", xlab="", ylab="", xaxs="i", yaxs="i")
          grid(17, 17, lty=1)
          for(i in r) try(points(i%%16, i%/%16, pch=sign*i, font=font,...))
       }
TestChars()
try(TestChars(sign=-1))
try(TestChars(font=5))

Plots

Density curve

hist(mtcars$mpg, breaks=12)
dens<-density(mtcars$mpg)
lines(dens$x,dens$y*100,col="red")

Pie

x<-table(mtcars$gear)
pie(x,label=paste0("gear=",rownames(x)))

Dotplot

Dotplot: Grouped Sorted and Colored Sort by mpg, group and color by cylinder

x <- mtcars[order(mtcars$mpg),] # sort by mpg
x$cyl <- factor(x$cyl) # it must be a factor
x$color[x$cyl==4] <- "red"
x$color[x$cyl==6] <- "blue"
x$color[x$cyl==8] <- "darkgreen"    
dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl,
                 main="Gas Milage for Car Models grouped by cylinder",
               xlab="Miles Per Gallon", gcolor="black", color=x$color)

Box plot

符号 示例 意义
+ +x 包括该变量
-x 不包括该变量
: x:z 包括两变量的相互关系
* x*z 包括两变量,以及它们之间的相互关系
/ x/z nesting: include z nested within x
| x|z 条件或分组:包括指定z的x
^ (u+v+w)^3 include these variables and all interactions up to three way
poly poly(x,3) polynomial regression: orthogonal polynomials
Error Error(a/b) specify the error term
I I(x*z) as is: include a new variable consisting of these variables multiplied
1 -1 截距:减去该截距
par(mfrow = c(1, 3))
boxplot(len ~ dose, data=ToothGrowth)
boxplot(len ~ interaction(dose,supp), data=ToothGrowth)
plot(len ~ interaction(dose,supp), data=ToothGrowth)

attach(mtcars)
par(mfrow = c(1, 2))
boxplot(mpg ~ cyl, data = mtcars, main = "Car Milage Data", xlab = "Number of Cylinders", 
    ylab = "Miles Per Gallon")
boxplot(len ~ supp * dose, data = ToothGrowth, notch = TRUE, col = (c("gold", 
    "darkgreen")), main = "Tooth Growth", xlab = "Suppliment and Dose")
## Warning in bxp(list(stats = structure(c(8.2, 9.7, 12.25, 16.5, 21.5, 4.2, :
## some notches went outside hinges ('box'): maybe set notch=FALSE

detach(mtcars)

Coplot

coplot(len ~ dose | supp, data = ToothGrowth, panel = panel.smooth,
       xlab = "ToothGrowth data: length vs dose, given type of supplement")

Multiplot

左下角为坐标(0,0),右上角为(1,1)的一个坐标系。fig=c(x1,x2,y1,y2),x1<x2,y1<y2.

使用new=TRUE参数来确认是否在原画布上继续画,还重新在一张新画布上开始画。

attach(mtcars)
par(fig=c(0,0.85,0,0.85))
plot(wt, mpg, xlab="Miles Per Gallon",ylab="Car Weight")
box("inner", lty="dotted", col="yellow")
par(fig=c(0,0.8,0.55,1), new=T)
boxplot(wt, horizontal=TRUE, axes=F)
par(fig=c(0.65,1,0,0.8),new=T)
boxplot(mpg, axes=FALSE)
mtext("Enhanced Scatterplot", side=3, outer=T, line=-3)
par(fig=c(0.4,0.75,0.4,0.7),new=T,mar=c(2,2,0,0),mgp=c(1,.4,0),cex=1,cex.lab=1,cex.axis=0.7)
hist(mpg, main="")

detach(mtcars)
def.par <- par(no.readonly = TRUE) # save default, for resetting...

x <- pmin(3, pmax(-3, rnorm(50)))
y <- pmin(3, pmax(-3, rnorm(50)))
xhist <- hist(x, breaks=seq(-3,3,0.5), plot=FALSE)
yhist <- hist(y, breaks=seq(-3,3,0.5), plot=FALSE)
top <- max(c(xhist$counts, yhist$counts))
xrange <- c(-3,3)
yrange <- c(-3,3)
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE)
#layout.show(nf)

par(mar=c(3,3,1,1))
plot(x, y, xlim=xrange, ylim=yrange, xlab="", ylab="")
par(mar=c(0,3,1,1))
barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)
par(mar=c(3,0,1,1))
barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)

par(def.par)

REFERENCES

  • ?pch
  • polygon
  • ?ploypath
  • library(help = "grDevices")