需要安装的包:

install.packages(c("RColorBrewer","lattice","survival","ggplot2","Formula","mice"))

R语言的绘图系统:

  • 第一代绘图系统
  • 基于lattic 的系统
  • 基于ggplot2 的绘图系统

绘图初步

绘图例子

par(ask=FALSE)
par(pin=c(5, 3))
temp <- par(pin <- c(4.2,2.3))
par(temp)
## named list()
#par(ask=TRUE)
#win.graph(width=4.875, height=2.5,pointsize=8)
opar <- par(no.readonly=TRUE) # make a copy of current settings
#win.graph(width=4.875, height=2.5,pointsize=8)
attach(mtcars) # be sure to execute this line
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")

detach(mtcars)

保存到文件

使用pdf() 函数:

pdf("mygraph.pdf")
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("Regression of MPG on Weight")
detach(mtcars)
dev.off()
## png 
##   2

除了pdf(),还可以使用函数win.metafile()、png()、jpeg()、bmp()、tiff()、xfig()postscript()将图形保存为其他格式。

对数据集绘图

例子

drug example

drug example

# Input data for drug example
dose  <- c(20, 30, 40, 45, 60)
drugA <- c(16, 20, 27, 40, 60)
drugB <- c(15, 18, 25, 31, 40)
#win.graph(width=4.875, height=2.5,pointsize=8)
plot(dose, drugA, type="b")

图形参数

通过函数par()来指定绘图选项

?par()

修改参数

使用实心三角而不是空心圆圈作为点的符号,并且想用虚线代替实线连接这些点:

opar <- par(no.readonly=TRUE) # make a copy of current settings
par(lty=2, pch=17)            # change line type and symbol
plot(dose, drugA, type="b")   # generate a plot

par(opar)                     # restore the original settings 
符号和线条类型的参数

符号和线条类型的参数

符号和线条类型的参数

符号和线条类型的参数

符号和线条类型的参数

符号和线条类型的参数

plot(dose, drugA, type="b", lty=3, lwd=3, pch=15, cex=2)

修改颜色

指定颜色的参数

指定颜色的参数

# choosing colors
library(RColorBrewer)
n <- 7
mycolors <- brewer.pal(n, "Set1")
barplot(rep(1,n), col=mycolors)

颜色集合的选择可以使用包RColorBrewer

n <- 10
mycolors <- rainbow(n)
pie(rep(1, n), labels=mycolors, col=mycolors)

mygrays <- gray(0:n/n)
pie(rep(1, n), labels=mygrays, col=mygrays)

使用col()改变颜色

# - Using graphical parameters to control graph appearance  
opar <- par(no.readonly=TRUE)
par(pin=c(2, 3))
par(lwd=2, cex=1.5)
par(cex.axis=.75, font.axis=3)
#win.graph(width=4.875, height=2.5,pointsize=8)
plot(dose, drugA, type="b", pch=19, lty=2, col="red")

plot(dose, drugB, type="b", pch=23, lty=6, col="blue", bg="green")

par(opar)       

添加文本、自定义坐标轴和图例

# Adding text, lines, and symbols
#win.graph(width=4.875, height=2.5,pointsize=8)
plot(dose, drugA, type="b",  
     col="red", lty=2, pch=2, lwd=2,
     main="Clinical Trials for Drug A", 
     sub="This is hypothetical data", 
     xlab="Dosage", ylab="Drug Response",
     xlim=c(0, 60), ylim=c(0, 70))

# Listing 3.2 - An Example of Custom Axes
x <- c(1:10)
y <- x
z <- 10/x
opar <- par(no.readonly=TRUE)
par(mar=c(5, 4, 4, 8) + 0.1)
plot(x, y, type="b",
     pch=21, col="red",
     yaxt="n", lty=3, ann=FALSE)
lines(x, z, type="b", pch=22, col="blue", lty=2)
axis(2, at=x, labels=x, col.axis="red", las=2)
axis(4, at=z, labels=round(z, digits=2),
     col.axis="blue", las=2, cex.axis=0.7, tck=-.01)
mtext("y=1/x", side=4, line=3, cex.lab=1, las=2, col="blue")
title("An Example of Creative Axes",
      xlab="X values",
      ylab="Y=X")

par(opar)
# Listing 3.3 - Comparing Drug A and Drug B response by dose
dose <- c(20, 30, 40, 45, 60)
drugA <- c(16, 20, 27, 40, 60)
drugB <- c(15, 18, 25, 31, 40)
opar <- par(no.readonly=TRUE)
par(lwd=2, cex=1.5, font.lab=2)
#win.graph(width=4.875, height=2.5,pointsize=8)
plot(dose, drugA, type="b",
     pch=15, lty=1, col="red", ylim=c(0, 60),
     main="Drug A vs. Drug B",
     xlab="Drug Dosage", ylab="Drug Response")
lines(dose, drugB, type="b",
      pch=17, lty=2, col="blue")
abline(h=c(30), lwd=1.5, lty=2, col="gray")
library(Hmisc)
## Loading required package: lattice
## Loading required package: survival
## Loading required package: Formula
## Loading required package: ggplot2
## 
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:base':
## 
##     format.pval, round.POSIXt, trunc.POSIXt, units
minor.tick(nx=3, ny=3, tick.ratio=0.5)
legend("topleft", inset=.05, title="Drug Type", c("A","B"), lty=c(1, 2), pch=c(15, 17), col=c("red", "blue"))

par(opar)
# Example of labeling points
attach(mtcars)
## The following object is masked from package:ggplot2:
## 
##     mpg
#win.graph(width=8.875, height=8.5,pointsize=8)
plot(wt, mpg,
     main="Mileage vs. Car Weight",
     xlab="Weight", ylab="Mileage",
     pch=18, col="blue")
text(wt, mpg,
     row.names(mtcars),
     cex=0.6, pos=4, col="red")

detach(mtcars)
# View font families 
opar <- par(no.readonly=TRUE)
par(cex=1.5)
#win.graph(width=4.875, height=2.5,pointsize=8)
plot(1:7,1:7,type="n")
text(3,3,"Example of default text")
text(4,4,family="mono","Example of mono-spaced text")
text(5,5,family="serif","Example of serif text")

par(opar)
# Combining graphs
attach(mtcars)
## The following object is masked from package:ggplot2:
## 
##     mpg
opar <- par(no.readonly=TRUE)
par(mfrow=c(2,2))
par(ask=FALSE)
plot(wt,mpg, main="Scatterplot of wt vs. mpg")
plot(wt,disp, main="Scatterplot of wt vs. disp")
hist(wt, main="Histogram of wt")
boxplot(wt, main="Boxplot of wt")

par(opar)
detach(mtcars)
attach(mtcars)
## The following object is masked from package:ggplot2:
## 
##     mpg
opar <- par(no.readonly=TRUE)
#win.graph(width=4.875, height=2.5,pointsize=8)
par(mfrow=c(3,1))
hist(wt)
hist(mpg)
hist(disp)

par(opar)
detach(mtcars)
attach(mtcars)
## The following object is masked from package:ggplot2:
## 
##     mpg
layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE))
hist(wt)
hist(mpg)
hist(disp)

detach(mtcars)
attach(mtcars)
## The following object is masked from package:ggplot2:
## 
##     mpg
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)

detach(mtcars)
# Listing 3.4 - Fine placement of figures in a graph
opar <- par(no.readonly=TRUE)
par(fig=c(0, 0.8, 0, 0.8))
plot(mtcars$mpg, mtcars$wt,
     xlab="Miles Per Gallon",
     ylab="Car Weight")
par(fig=c(0, 0.8, 0.55, 1), new=TRUE)
boxplot(mtcars$mpg, horizontal=TRUE, axes=FALSE)
par(fig=c(0.65, 1, 0, 0.8), new=TRUE)
boxplot(mtcars$wt, axes=FALSE)
mtext("Enhanced Scatterplot", side=3, outer=TRUE, line=-3)

par(opar)

绘图实例

实例(一)

cit  <- c(     2010, 37, 182, NA,
               2009, 36, 129, NA,
               2008, 27, 111, NA,
               2007, 35, 136, NA,
               2006, 18, 80, NA,
               2005, 20, 76, NA,
               2004,  6, 56, NA,
               2003, 17, 42, NA,
               2002, 14, 40, NA,
               2001, 13, 36, 57,
               2000,  8, 21, 33,
               1999,  6, 25, 47,
               1998, 6, 13, 22,
               1997, 6, 18, 29,
               1996, 4, 12, 28,
               1995, 3, 5, 20,
               1994, 2, 5, 34,
               1993, 2, 6, 15,
               1991, 2, 4, 19,
               1990, 1, 2, 15,
               1989, NA, NA, 11,
               1988, 1, NA, 13,
               1987, NA, NA, 10,
               1986, NA, NA, 5,
               1985, NA, NA, 1,
               1984, NA, NA, 2,
               1983, NA, NA, 5,
               1982, NA, NA, 2,
               1981, NA, NA, 1,
               1980, NA, NA, 5,
               1979, NA, NA, 2,
               1978, NA, NA, 1,
               1977, NA, NA, 2)
cit <- matrix(cit, nr=2010-1977, nc=4, byrow=TRUE)
cit <- as.data.frame(cit)
names(cit) <- c("Year","Title","Abstract","All")
par(mfrow=c(1,1))
par(cex=0.7, lwd=0.5)
plot(x=cit$Year, y=cit$Abstract, type="o",log="y",
     xlim=c(1975,2010),ylim=c(1,200),
     ylab="Number of publications (log)", xlab="Year", pch=2, 
     axes=FALSE)
axis(1, lwd=par("lwd"))
axis(2, lwd=par("lwd"), las=1)
# box(lwd=0.5)
lines(x=cit$Year, y=cit$Title, pch=15, type="o")
lines(x=cit$Year, y=cit$All, pch=16, type="o")
legend(x=1975,y=200,legend=c("early publications",
                             "'multiple imputation' in abstract",
                             "'multiple imputation' in title"),
       pch=c(16,2,15), bty="n")

实例(二)

library("MASS")
library("mice")
## Loading required package: Rcpp
## mice 2.25 2015-11-09
library("lattice")

logistic <- function(x) exp(x)/(1+exp(x))
set.seed(80122)
n <- 300
y <- mvrnorm(n=n,mu=c(0,0),Sigma=matrix(c(1,0.5,0.5,1),nrow=2))
y1 <- y[,1]
y2 <- y[,2]
r2.mcar <- 1-rbinom(n, 1, 0.5)
r2.mar  <- 1-rbinom(n, 1, logistic(y1))
r2.mnar <- 1-rbinom(n, 1, logistic(y2))

### Figure 2.2

y3 <- rbind(y,y,y)
r2 <- c(r2.mcar,r2.mar,r2.mnar)
r2 <- factor(r2, labels=c("Ymis","Yobs"))
typ <- factor(rep(3:1,each=n),labels=c("MNAR","MAR","MCAR"))
d <- data.frame(y1=y3[,1],y2=y3[,2],r2=r2,typ=typ)
trellis.par.set(box.rectangle=list(col=c(mdc(2),mdc(1)),lwd=1.2))
trellis.par.set(box.umbrella=list(col=c(mdc(2),mdc(1)),lwd=1.2))
trellis.par.set(plot.symbol=list(col=mdc(3),lwd=1))
tp <- bwplot(r2~y2|typ, data=d,
             horizontal=TRUE, layout=c(1,3),
             xlab=expression(Y^2),
             col=c(mdc(2),mdc(1)),strip=FALSE, xlim=c(-3,3),
             strip.left = strip.custom(bg="grey95"))
print(tp)

返回课程主页