本篇文章是关于如何在R中使用plot函数来建立图形系列文章的第一篇。固然,R中还有其余的包能够建立很酷的图形(如ggplot2
或lattice
)。不过plot函数也能够知足咱们基本的绘图要求。函数
在这篇文章,咱们能够学习到如何在散点图中添加信息,如何添加图例,最后在图中添加回归线。学习
#模拟数据 dat<-data.frame(X=runif(100,-2,2),T1=gl(n=4,k=25,labels=c("Small","Medium","Large","Big")),Site=rep(c("Site1","Site2"),time=50)) mm<-model.matrix(~Site+X*T1,dat) betas<-runif(9,-2,2) dat$Y<-rnorm(100,mm%*%betas,1) summary(dat)
首先,plot函数能够用不一样的方式来添加颜色。一种方式是给plot的col
参数传递一个颜色向量。spa
#选择须要使用的颜色 library(RColorBrewer) #RColorBrewer中的全部调色板 display.brewer.all() #选取Set1调色板中的四种颜色 cols<-brewer.pal(n=4,name="Set1") #cols表示的是四种不一样颜色的名称 #建立一个跟T1变量的因子水平相对应的颜色向量 cols_t1<-cols[dat$T1] plot(Y~X,dat,col=cols_t1,pch=16)
建立图形符号向量,用来标记两种不一样的Site
。以下所示:翻译
pch_site<-c(16,18)[factor(dat$Site)] #pch参数用来控制图形符号 plot(Y~X,dat,col=cols_t1,pch=pch_site)
如今给图形添加图例:code
plot(Y~X,dat,col=cols_t1,pch=pch_site) legend("topright",legend=paste(rep(c("Small","Medium","Large","Big"),times=2),rep(c("Site 1","Site 2"),each=4),sep=", "),col=rep(cols,times=2),pch=rep(c(16,18),each=4),bty="n",ncol=2,cex=0.7,pt.cex=0.7)
legend
函数的第一个参数指定图例显示在图形中的位置,接着是图例的文本。其它可参数包括指定图例的颜色,图形符号等。更多详情可经过?legend
查看。orm
经过设置xpd=TRUE
能够在图形外增长图例。并指定x,y坐标轴。ci
plot(Y~X,dat,col=cols_t1,pch=pch_site) legend(x=-1,y=13,legend=paste(rep(c("Small","Medium","Large","Big"),times=2),rep(c("Site 1","Site 2"),each=4),sep=", "),col=rep(cols,times=2),pch=rep(c(16,18),each=4),bty="n",ncol=2,cex=0.7,pt.cex=0.7,xpd=TRUE)
#generate a new data frame with ordered X values new_X<-expand.grid(X=seq(-2,2,length=10),T1=c("Small","Medium","Large","Big"),Site=c("Site1","Site2")) #the model m<-lm(Y~Site+X*T1,dat) #get the predicted Y values pred<-predict(m,new_X) #plot xs<-seq(-2,2,length=10) plot(Y~X,dat,col=cols_t1,pch=pch_site) lines(xs,pred[1:10],col=cols[1],lty=1,lwd=3) lines(xs,pred[11:20],col=cols[2],lty=1,lwd=3) lines(xs,pred[21:30],col=cols[3],lty=1,lwd=3) lines(xs,pred[31:40],col=cols[4],lty=1,lwd=3) lines(xs,pred[41:50],col=cols[1],lty=2,lwd=3) lines(xs,pred[51:60],col=cols[2],lty=2,lwd=3) lines(xs,pred[61:70],col=cols[3],lty=2,lwd=3) lines(xs,pred[71:80],col=cols[4],lty=2,lwd=3) legend(x=-1,y=13,legend=paste(rep(c("Small","Medium","Large","Big"),times=2),rep(c("Site 1","Site 2"),each=4),sep=", "),col=rep(cols,times=2),pch=rep(c(16,18),each=4),lwd=1,lty=rep(c(1,2),each=4),bty="n",ncol=2,cex=0.7,pt.cex=0.7,xpd=TRUE)
还能够在绘图区域添加许多图形元素,例如:points
,lines
,rect
,text
。get
后面的文章会继续介绍如何控制轴标签和刻度线。it
本文由雪晴数据网负责翻译整理,原文请参考Mastering R Plot – Part 1: colors, legends and lines做者Lione Hertzog。转载本译文请注明连接http://www.xueqing.cc/cms/article/117 io