Created
December 13, 2011 04:55
-
-
Save yihui/1470665 to your computer and use it in GitHub Desktop.
change the binwidth of 2D KDE with rgl and gWidgets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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