# R in action读书笔记（4）-第六章：基本图形（下）

6.3直方图

hist()

par(mfrow=c(2，2))

hist(mtcars\$mpg)#简单直方图

hist(mtcars\$mpg#指定组数和颜色

breaks=12

col="red"

xlab="Miles Per Gallon"

main="Colored histogram wi七h 12 bins

hist(mtcars\$mpg#添加轴须图

freq=FALSE,

breaks=12

col=”red"

xlab="Miles Per Gallon"

main="His七ogram, rug plo七，densi七y curve"

rug(jitter(mtcars\$mpg))

lines(density(mtcars字mpg)，col="blue"，lwd=2)

x<一mtcars\$mpg#添加正态密度曲线和外框

h<-hist(x,

breaks=12

col=”red"

xlab="Mfiles Per Gallon"

main="Histogramwith normal curve and box"

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()

6.4核密度图

par(mfrow=c(2，1))

d<一density(mtcars\$mpg)

plot(d)

d<一density(mtcars\$mpg)

plot(d, main=”Kernel Density of Miles Per Gallon"

polygon(d, col=”red"，border="blue”)# polygon()函数根据顶点的x和y坐标（本例中由density()函数提供）绘制了多边形。

rug(mtcars\$mpg, col=”brown”)

sm .density .compare(x, factor)

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 Distribution by Car Cylinders”)

colfill<-c(2:(1+length(levels(cyl.f)))) #通过鼠标单击添加图例

legend(locator(1)，levels(cyl .f)，fill=colfill)

detach(mtcars)

6.5箱线图

boxplot(mtcars\$mpg,main=”box plot”,ylab=”miles per gallon”)

6.5.1使用并列箱线图进行跨组比较

boxplot(formula，data=data framel)

A，这将为类别型变量A的每个值并列地生成数值型变量y的箱线图。公式y ~ A*B则将为类别型

boxplot(mpg~cyl,data=mtcars,main="Car mileage data",xlab="number of cylinders",ylab="miles per gallon")

boxplot(mpg~cyl,data=mtcars,notch=TRUE,varwidth=TRUE,col="red",main="Car Mileage Data",xlab="Number of Cylinders",ylab="Miles Per Gallon")

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=TRUE,col=c("gold","darkgreen"),main="MPG Distribution by Auto Type",xlab="Auto Type")#生成箱线图

6.5.2小提琴图

>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 cyl","6 cyl","8 cly"),col="gold")

> title("violin plots of miles per gallon")

6.6点图

dotchart(mtcars\$mpg,labels=row.names(mtcars),cex=0.7,main="gas mileage for car nolels",xlab="miles per gallon")

> 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=row.names(x),cex=.7,groups=x\$cyl,gcolor="black",color=x\$color,pch=19,main="gas fo car models\ngrouped by cylinder",xlab="miles per gallon")