rgl 包有一个函数 hist3d(实际上不在文档中,但您可以调用它并查看代码)。
虽然这个 hist3d 是,但对我来说,在 3 维中显示 2 维直方图(输入 = x,y)。
如果这是你想要的代码(来自 rgl):
> hist3d
function(x,y=NULL,nclass="auto",alpha=1,col="#ff0000",scale=10)
{
save <- par3d(skipRedraw=TRUE)
on.exit(par3d(save))
xy <- xy.coords(x,y)
x <- xy$x
y <- xy$y
n<-length(x)
if (nclass == "auto") { nclass<-ceiling(sqrt(nclass.Sturges(x))) }
breaks.x <- seq(min(x),max(x),length=(nclass+1))
breaks.y <- seq(min(y),max(y),length=(nclass+1))
z<-matrix(0,(nclass),(nclass))
for (i in 1:nclass)
{
for (j in 1:nclass)
{
z[i, j] <- (1/n)*sum(x < breaks.x[i+1] & y < breaks.y[j+1] &
x >= breaks.x[i] & y >= breaks.y[j])
binplot.3d(c(breaks.x[i],breaks.x[i+1]),c(breaks.y[j],breaks.y[j+1]),
scale*z[i,j],alpha=alpha,topcol=col)
}
}
}
我构建了自己的 hist3d 以返回 3 维直方图(例如用于红绿蓝):
my_hist3d <- function(x,y=NULL,z=NULL, nclass="auto",alpha=1,col="#ff0000",scale=10)
{
xyz <- xyz.coords(x,y,z)
x <- xyz$x
y <- xyz$y
z <- xyz$z
n<-length(x)
if (nclass == "auto") { nclass<-ceiling(sqrt(nclass.Sturges(x))) }
breaks.x <- seq(min(x),max(x),length=(nclass+1))
breaks.y <- seq(min(y),max(y),length=(nclass+1))
breaks.z <- seq(min(z),max(z),length=(nclass+1))
h = array(1:(nclass^3), dim=c(nclass,nclass,nclass))
for (i in 1:nclass)
{
for (j in 1:nclass)
{
for (k in 1:nclass)
{
h[i,j,k] <- (1/n)*sum(x < breaks.x[i+1] & y < breaks.y[j+1] & x >= breaks.x[i] & y >= breaks.y[j] & z < breaks.z[k+1] & z >= breaks.z[k])
}
}
}
return(h)
}
返回的变量 (h) 是一个大小为 nclass^3 的三维矩阵(nclass 是每个维度的 bin 数)。