1 多组图
setwd("E:/R/R-beginer-guide/data/RBook") Benthic <- read.table(file="RIKZ2.txt",header = TRUE) pairs(Benthic[,2:9])效果:
上图每个图形都重复了一遍
解决:
pairs(Benthic[,2:9],diag.panel=panel.hist, upper.panel=panel.smooth, lower.panel=panel.cor)在R控制台中执行报错:
+ lower.panel=panel.cor) 错误于pairs.default(Benthic[, 2:9], diag.panel = panel.list, upper.panel = panel.smooth, : 找不到对象'panel.cor'解决这个错误
手下在控制台敲入:
? pairs弹出的页面中可以找到两函数
第一个
panel.hist <- function(x, ...) { usr <- par("usr"); on.exit(par(usr)) par(usr = c(usr[1:2], 0, 1.5) ) h <- hist(x, plot = FALSE) breaks <- h$breaks; nB <- length(breaks) y <- h$counts; y <- y/max(y) rect(breaks[-nB], 0, breaks[-1], y, col="cyan", ...) }第二个
panel.cor <- function(x, y, digits=2, prefix="", cex.cor, ...) { usr <- par("usr"); on.exit(par(usr)) par(usr = c(0, 1, 0, 1)) r <- abs(cor(x, y)) txt <- format(c(r, 0.123456789), digits=digits)[1] txt <- paste(prefix, txt, sep="") if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt) text(0.5, 0.5, txt, cex = cex.cor * r) }错误心中报的是
找不到对象'panel.cor'因此在R控制台执行第二个函数
然后在执行pair函数就可得到正确的效果图
2 协同图
实战1
coplot(Richness ~ NAP | as.factor(Beach),pch=19,data=Benthic)效果:
实战2
coplot(Richness ~ NAP | grainsize,pch=19,data=Benthic)效果略
实战3
panel.lm=function(x,y,...) { tmp <- lm(y ~ x,na.action = na.omit) abline(tmp) points(x,y,...) } coplot(Richness ~ NAP |as.factor(Beach), pch=19,panel=panel.lm,data = Benthic)
实战4 两个条件变量的协同图
pHEire <- read.table(file="SDI2003.txt",header = TRUE) pHEire$LOGAlt <- log10(pHEire$Altitude) pHEire$fForested <- factor(pHEire$Forested) coplot(pH ~ SDI | LOGAlt * fForested, panel=panel.lm,data=pHEire)实战5
pHEire$Temp2 <- cut(pHEire$Temperature,breaks=2) pHEire$Temp2.num <- as.numeric(pHEire$Temp2) coplot(pH ~ SDI | LOGAlt*fForested, panel=panel.lm,data = pHEire, number = 3,cex=1.5,pch=19, col = gray(pHEire$Temp2.num/3))3 组合不同类型的图
MyLayOut <- matrix(c(2,0,1,3),nrow=2,ncol=2,byrow=TRUE) MyLayOut nf <- layout(mat = MyLayOut,widths = c(3,1), heights = c(1,3),respect = TRUE) show(nf) xrange <- c(min(Benthic$NAP),max(Benthic$NAP)) yrange <- c(min(Benthic$Richness),max(Benthic$Richness)) #First graph par(mar = c(4,4,2,2)) plot(Benthic$NAP,Benthic$Richness , frame.plot = FALSE,xlim = xrange,ylim = yrange,ylab = "Richness") #Second graph par(mar = c(0,3,1,1)) boxplot(Benthic$NAP,horizontal=TRUE,axes = FALSE, frame.plot = FALSE,ylim= xrange,space = 0) #Third graph par(mar=c(3,0,1,1)) boxplot(Benthic$Richness,axes = FALSE,ylim = yrange,space = 0,horiz= TRUE)