Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
change the binwidth of 2D KDE with rgl and gWidgets
## adpated from demo('bivar') in rgl
rgl.demo.bivar = function(x, y, bw, ngrid = 25, ...) {
library(MASS); library(rgl)
n = length(x)
denobj = kde2d(x, y, bw, n = ngrid)
den.z = denobj$z; xgrid = denobj$x; ygrid = denobj$y
bi.z = dnorm(xgrid) %*% t(dnorm(ygrid))
zscale = 20; clear3d()
spheres3d(x, y, rep(0, n), radius = 0.1, color = "#CCCCFF")
surface3d(xgrid, ygrid, den.z * zscale, color = "#FF2222", alpha = 0.5)
surface3d(xgrid, ygrid, bi.z * zscale, color = "#CCCCFF", front = "lines")
}
set.seed(31415)
n = 50; x = rnorm(n); y = rnorm(n)
rgl.demo.bivar(x, y, 2)
## change binwidth interactively
library(gWidgetsRGtk2)
options(guiToolkit = 'RGtk2')
gslider(from = 0.1, to = 10, by = 0.1,
container = gwindow("Change binwidth"),
handler = function(h, ...) {
rgl.demo.bivar(x, y, bw = svalue(h$obj))
})
## what you should really do
res = kde2d(x, y)
contour(res$x, res$y, res$z)
points(x, y, pch = 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.