## ---------------------------------------------------------------------------- ## R scripts for Haerdle/Mueller/Sperlich/Werwatz: "Nonparametric and ## Semiparametric Modelling", Springer Series in Statistics, 2004 ## ---------------------------------------------------------------------------- ## Script SPMdensity2D-RGL ## ---------------------------------------------------------------------------- ## Description estimates a bivariate density and shows the resultng KDE ## as a 3D graph and as a contour plot (with additional rgl ## 3D graph to be rotated) ## ---------------------------------------------------------------------------- ## Author Marlene Mueller, 2010/07/11 ## ---------------------------------------------------------------------------- library(AER) library(KernSmooth) library(rgl) data <- data("CPS1985") x <- CPS1985[,c("age","wage")] n <- nrow(x) sd <- sd(x) h <- sd * n^(-1/6) ## Scott's rule of thumb est <- bkde2D(x, bandwidth=h) par(mfrow=c(1,2)) persp(est$fhat, theta = 30, phi = 30, expand = 0.5, col = "lightblue", main="2D Density Estimate", xlab="age", ylab="wage", zlab="KDE") contour(est$x1, est$x2, est$fhat, nlevels=20, main="2D Density Contours", xlab="age", ylab="wage") par(mfrow=c(1,1)) ## rgl perspective plot persp3d(est$x1, est$x2, est$fhat, aspect=c(1, 1, 0.5), col = "lightblue", xlab="age", ylab="wage", zlab="fh")