DrawDensity = function(x,bw=5)
{
if(any(bw<=0))
{
bw <- 5
}
#print(bw)
n <- length(x)
if(any(n>0))
{
mn <- min(x)
mx <- max(x)
rmn <- (mn %/% bw)
begx <- rmn * bw
rmn <- (mx %/% bw)
endx <- (rmn) * bw
if ((mx-rmn * bw) > 0)
{
endx <- (rmn+1) * bw
}
segs <- (endx-begx) %/% bw
segcounts <- numeric(segs)
validsegs <- 0
print(segs)
for(i in 1:segs)
{
slw <- begx+(i-1) * bw
sup <- begx+(i) * bw
tmp<- x[x > slw & x<=sup];
segcounts[i]<- length(tmp)
if(length(tmp)>0)
{
validsegs <- validsegs+1
}
}
#计算基本密度:向量长度与图形分割宽度的积倒数.
baseIndesity = 1 / (n*bw);
ymax = baseIndesity * (max(segcounts)+1)
plot(c(begx,endx),c(0,0),xlim=c(begx,endx),ylim=c(0,ymax))
lines(c(begx,endx),c(0,0))
lines(c(0,0),c(0,ymax))
#print(segs)
for (i in 1:segs)
{
x1 <- begx+(i-1) * bw
x2 <- begx+(i) * bw
y<- baseIndesity * segcounts[i]
drawHist(x1,x2,y)
#print(i)
}
}
}
drawHist = function(x1,x2,y)
{
#print(x1);print(x2);print(y)
lines(c(x1,x1),c(0,y))
lines(c(x1,x2),c(y,y))
lines(c(x2,x2),c(0,y))
}