分享

R语言画图大全(实战3,6,11)

 勤悦轩 2016-08-26
  #图形初阶
#例1(画图)
attach(mtcars)#绑定数据框mtcars
plot(wt,mpg)
abline(lm(mpg~wt))#添加最优拟合曲线
title("Regression of MPG on weight")
detach(mtcars)#对数据框删除绑定

#例2(保存图)
setwd("D:/桌面/R语言学习")
png("mygraph.png")
attach(mtcars)#绑定数据框mtcars
plot(wt,mpg)
abline(lm(mpg~wt))#添加最优拟合曲线
title("Regression of MPG on weight")
detach(mtcars)#对数据框删除绑定
dev.off()

#例3(打开新的图形窗口)
dev.new()
attach(mtcars)#绑定数据框mtcars
plot(wt,mpg,col="red")

detach(mtcars)#对数据框删除绑定


dev.new()
attach(mtcars)#绑定数据框mtcars
plot(wt,mpg,col="blue")
abline(lm(mpg~wt))#添加最优拟合曲线

detach(mtcars)#对数据框删除绑定


dev.new()
attach(mtcars)#绑定数据框mtcars
plot(wt,mpg,col="green")
abline(lm(mpg~wt))#添加最优拟合曲线
title("Regression of MPG on weight")
detach(mtcars)#对数据框删除绑定

#例4
dose<-c(20,30,40,45,60)
drugA<-c(16,20,27,40,60)
drugB<-c(15,18,25,31,40)
plot(dose,drugA,type="b")#b表示同时画点和线


par(optinname=value,...)#设置当前图形参数,除非再次修改,否则将在会话结束前一直有效
pch#指定绘制点使用的符号
lty#指定线条类型
lwd#指定线条宽度
fg#图形的前景色
bg#图形的背景色


col#绘图颜色
col.axis#坐标轴刻度文字的颜色
col.lab#坐标轴标签的颜色
col.main#标题颜色
col.sub#副标题颜色
#文本大小
cex#指定绘制点符号的大小
cex.axis#坐标轴刻度文字的缩放倍数
cex.lab#
cex.main#
cex.sub#
#字体
font#指定绘图使用的字体样式
font.axis#
font.lab#
font.main#
font.sub#

#例5
opar<-par(no.readonly=T)#复制当前的图形参数设置
par(lty=2,pch=17)
plot(dose,drugB,type="b")
par(opar)

#例6
n<-10
mycolors<-rainbow(n)
pie(rep(1,n),labels=mycolors,col=mycolors)
mygrays<-gray(0:n/n)
pie(rep(1,n),lables=mygrays,col=mygrays)


title(main="",sub="",xlab="",ylab="")#为图形添加标题和坐标轴标签
axis(side,at=,labels=,pos=,...)#创建自定义的坐标轴
side #在图形的哪边绘制坐标轴(1下,2左,3上,4右)
at #需要绘制刻度线的位置
labels #置于刻度线旁边的文字标签 
pos #坐标轴线绘制位置的坐标
las #标签是否平行于(0)或垂直于(2)坐标轴
tck #刻度线的长度,以相对于绘图区域大小的分数表示
#例7
x<-c(1:10)
y<-x
z<-10/x
opar<-par(no.readonly=T)
par(mar=c(5,4,4,8)+0.1)#增加边界大小
plot(x,y,type="b",pch=21,yaxt="n",ann=FALSE)#ann=FALSE是移除默认的标题和标签
lines(x,z,type="b",pch=22,col="red")
axis(2,at=x,labels=x,col.axis="blue",las=2)#绘制坐标轴
axis(4,at=z,labels=round(z,digits=2),col.axis="green",cex.axis=0.7,las=2,tck=-0.01)
mtext("y=1/x",side=4,line=3,,cex.lab=1,las=2)#添加标题和文本
title("An Example of Creative Axes",xlab="X",ylab="Y=X")
par(opar)


abline(h=yvalues,v=xvalues) #为图形添加参考线
legend(location,title,legend,...) #添加图例
location #图例的位置,可以执行locator(1),单击鼠标给出位置
text() #向绘图区域内部添加文本
mtext() #向图形的四个边界之一添加文本

#例8(图形组合)
attach(mtcars)
opar<-par(mfrow=c(3,1))#图1
hist(wt)
hist(mpg)
hist(disp)
par(opar)


layout(matrix(c(1,1,2,3),2,2,byrow=T))#图2
hist(wt)
hist(mpg)
hist(disp)
detach(mtcars)


通过令fig=c(x1,x2,y1,y2)来完成图形布局的精细控制
#例9(图形布局)
opar<-par(no.readonly=T)
par(fig=c(0,0.8,0,0.8))
plot(mtcars$wt,mtcars$mpg)
par(fig=c(0,0.8,0.38,1),new=T)
boxplot(mtcars$wt,horizontal=T,axes=F)
par(fig=c(0.5,1,0,0.8),new=T)
boxplot(mtcars$mpg,axes=F)
mtext("Enhanced Scatterplot",side=3,outer=T,line=-3)
par(opar)


#基本图形
#例1(条形图)
library(grid)
library(vcd)#数据框Arthritis在包中
counts<-table(Arthritis$Improved)
counts
barplot(counts,xlab="Improvement",ylab="Frequency",horiz=T)#图1

#因为Arthritis$Improved是一个因子,故可直接使用plot,不需要用table
plot(Arthritis$Improved,horiz=T)#图2

#例2(堆砌条形图和分组条形图)
library(grid)
library(vcd)#数据框Arthritis在包中
counts<-table(Arthritis$Improved,Arthritis$Treatment)
counts
barplot(counts,xlab="Treatment",ylab="Frequency",col=c("red","blue","green"),legend=rownames(counts))#堆砌条形图


barplot(counts,xlab="Treatment",ylab="Frequency",col=c("red","blue","green"),legend=rownames(counts),beside=T)#分组条形图

#例3(均值条形图)
states<-data.frame(state.region,state.x77)
means<-aggregate(states$Illiteracy,by=list(state.region),FUN=mean)
means
means<-means[order(means$x,decreasing=F),] #从小到大排序
means
barplot(means$x,names.arg=means$Group.1)
title("Mean Illiteracy Rate")

#例4(棘状图)
library(grid)
library(vcd)
attach(Arthritis)
counts<-table(Treatment,Improved)
spine(counts)
detach(Arthritis)

#例5(饼图)
par(mfrow=c(2,2))
slices<-c(10,12,4,16,8)
lbls<-c("US","UK","Australia","Germany","France")
pie(slices,labels=lbls)

pct<-round(slices/sum(slices)*100)
lbls2<-paste(lbls," ",pct,"%",sep="")
pie(slices,labels=lbls2,col=rainbow(length(lbls2)))

library(plotrix)
pie3D(slices,labels=lbls,explode=0.1)

mytable<-table(state.region)
lbls3<-paste(names(mytable),"\n",mytable,sep="")
pie(mytable,labels=lbls3)


#例6(扇形图)
library(plotrix)
slices<-c(10,12,4,16,8)
lbls<-c("US","UK","Australia","Germany","France")
fan.plot(slices,labels=lbls)

#例7(直方图)
attach(mtcars)
par(mfrow=c(2,2))
hist(mpg)

hist(mpg,breaks=12,col="red")

hist(mpg,freq=F,breaks=12,col="blue")
rug(jitter(mpg)) #轴须图
lines(density(mpg),col="green",lwd=2)

x<-mpg
h<-hist(x,breaks=12,col="red",)
xfit<-seq(min(x),max(x),length=40)
yfit<-dnorm(xfit,mean=mean(x),sd=sd(x))
yfit<-yfit*diff(h$mids[1:2])*length(x)
lines(xfit,yfit,col="blue",lwd=2)
box()
detach(mtcars)

#例8(核密度图)
par(mfrow=c(2,1))
d<-density(mtcars$mpg)
plot(d)

plot(d)
polygon(d,col="red",border="blue")#绘制多边形
rug(mtcars$mpg,col="brown")


sm.density.compare(x,factor) #向图形中叠加两组或更多的核密度图
#例9(可比较的核密度图)
par(lwd=2)
library(sm)
attach(mtcars)
cyl.f<-factor(cyl,levels=c(4,6,8),labels=c("4 cylinder","6 cylinder","8 cylinder"))
sm.density.compare(mpg,cyl,xlab="Miles Per Gallon")
title(main="MPG by Cylinders")
colfill<-c(2:(1+length(levels(cyl.f))))
legend(locator(1),levels(cyl.f),fill=colfill)
detach(mtcars)

#例10(箱线图)
boxplot(mtcars$mpg)#图1

boxplot(mpg~cyl,data=mtcars)#图2

boxplot(mpg~cyl,data=mtcars,notch=T,varwidth=T,col="red")#图3
#notch=T #得到含凹槽的箱线图
#varwidth=T #使箱线图的宽度与其样本大小的平方根成正比

#例11(两个交叉因子的箱线图)
mtcars$cyl.f<-factor(mtcars$cyl,levels=c(4,6,8),labels=c("4","6","8"))
mtcars$am.f<-factor(mtcars$am,levels=c(0,1),labels=c("auto","standard"))
boxplot(mpg~am.f*cyl.f,data=mtcars,varwidth=T,col=c("gold","darkgreen"))

#例12(小提琴图)
library(vioplot)
x1<-mtcars$mpg[mtcars$cyl==4]
x2<-mtcars$mpg[mtcars$cyl==6]
x3<-mtcars$mpg[mtcars$cyl==8]
vioplot(x1,x2,x3,names=c("4","6","8"),col="gold")

#例13(点图)
dotchart(mtcars$mpg,labels=rownames(mtcars),cex=0.7)

#例14(分组、排序、着色后的点图)
x<-mtcars[order(mtcars$mpg),]
x$cyl<-factor(x$cyl)
x$color[x$cyl==4]<-"red"
x$color[x$cyl==6]<-"blue"
x$color[x$cyl==8]<-"darkgreen"
dotchart(x$mpg,labels=rownames(x),cex=0.7,groups=x$cyl,gcolor="black",color=x$color,pch=19)

#中级绘图
lowess() #平滑曲线拟合(基于局部加权多项式回归)
#例1
attach(mtcars)
plot(wt,mpg,pch=19)
abline(lm(mpg~wt),col="red",lty=1)
lines(lowess(wt,mpg),col="blue",lty=2)
detach(mtcars)

#例2
library(car)
scatterplot(mpg~wt|cyl,data=mtcars,legend.plot=T,id.method="identify",labels=row.names(mtcars),boxplots="xy")
#id.method="identify" #通过鼠标单击来交互式的识别数据点
#labels=row.names(mtcars) #通过点的行名来识别点
#legend.plot=T #表示在左上边界添加图例

#例3(散点图矩阵)
pairs(~mpg+disp+drat+wt,data=mtcars,upper.panel=NULL)
#upper.panel=NULL #只生成下三角的图形

#例4(散点图矩阵car包)
library(car)
scatterplotMatrix(~mpg+disp+drat+wt|cyl,data=mtcars,spread=F,diagonal="histogram")
#spread=F #表示不添加展示分散度和对称信息的直线

#例5(散点图矩阵gclus包)
library(gclus)
mydata<-mtcars[c(1,3,5,6)]
mydata.corr<-abs(cor(mydata))
mycolors<-dmat.color(mydata.corr)
myorder<-order.single(mydata.corr)
cpairs(mydata,myorder,panel.colors=mycolors,gap=0.5)

smoothScatter() #利用核密度估计生成用颜色密度来表示点分布的散点图
#例6(高密度散点图)
set.seed(123)
n<-1000
c1<-matrix(rnorm(n,0,0.5),ncol=2)
c2<-matrix(rnorm(n,3,2),ncol=2)
mydata<-rbind(c1,c2)
mydata<-as.data.frame(mydata)
names(mydata)<-c("x","y")
with(mydata,plot(x,y,pch=19))
with(mydata,smoothScatter(x,y))


#例7(三维散点图)
library(scatterplot3d)
attach(mtcars)
s3d<-scatterplot3d(wt,disp,mpg,pch=16,highlight.3d=T,type="h")
fit<-lm(mpg~wt+disp)
s3d$plane3d(fit)

#旋转三维散点图
library(rgl)
plot3d(wt,disp,mpg,col="red",size=5)

#包含回归曲面(默认线性)
library(Rcmdr)
scatter3d(wt,disp,mpg)
detach(mtcars)

symbols(x,y,circle=sqrt(z/pi)) #用面积表示第三个变量
#例8(气泡图)
attach(mtcars)
r<-sqrt(disp/pi)
symbols(wt,mpg,r,inches=0.3,fg="white",bg="lightblue")
text(wt,mpg,rownames(mtcars),cex=0.6)
detach(mtcars)


#例9(五种橘树随时间生长的折线图)
Orange$Tree<-as.numeric(Orange$Tree)
ntrees<-max(Orange$Tree)

xrange<-range(Orange$age)
yrange<-range(Orange$circumference)

plot(xrange,yrange,type="n")

colors<-rainbow(ntrees)
linetype<-c(1:ntrees)
plotchar<-seq(18,18+ntrees,1)

for(i in 1:ntrees){
 tree<-subset(Orange,Tree==i)
 lines(tree$age,tree$circumference,type="b",lwd=2,lty=linetype[i],col=colors[i],pch=plotchar[i])
}
legend(xrange[1],yrange[2],1:ntrees,cex=0.8,col=colors,pch=plotchar,lty=linetype,title="Tree")

#例10(相关图)

options(digits=2)

cor(mtcars)

library(corrgram)

corrgram(mtcars,order=T,lower.panel=panel.shade,upper.panel=panel.pie,text.panel=panel.txt)#图1

#order=T #相关阵使用主成分分析法对变量重排序
#lower.panel=panel.shade,upper.panel=panel.pie #下三角和上三角使用的元素类型

#text.panel=panel.txt #主对角线元素类型


corrgram(mtcars,order=T,lower.panel=panel.ellipse,upper.panel=panel.pts,text.panel=panel.txt,diag.panel=panel.minmax)#图2


corrgram(mtcars,lower.panel=panel.shade,upper.panel=NULL,text.panel=panel.txt)#图3

#例11(马赛克图)
ftable(Titanic)
library(vcd)
mosaic(Titanic,shade=T,legend=T)


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约