核密度估计是用于估计随机变量概率密度函数的一种非参数方法。
1. 核密度图
plot()函数,polygon()函数
d<- density(mtcars$mpg)
class(d)
plot(d)
# polygon()函数根据顶点的x和y坐标(本例中由density()函数提供)绘制了多边形。
polygon(d,col='red',border='blue')
rug(mtcars$mpg,col='brown')
2. 可比较的核密度图
sm包中的sm.density.compare()函数
# install.packages('sm')
library(sm)
attach(mtcars)
cyl.f <- factor(mtcars$cyl,labels=paste(c(4,6,8),"cylinder"))
colfill <- c(2:length(levels(cyl.f)))
sm.density.compare(mpg,cyl,xlable='Miles Per Gallon',
col=c("red","blue","green"))
title(main="MPG Distribution by Car Cylinders")
legend('topright',levels(cyl.f),fill=c("red","blue","green"))
# locator(1) 添加图例到鼠标点击的位置
# legend(locator(1),levels(cyl.f),fill=colfill)
detach(mtcars)