########################## ## Voronoi ########################## library(class) Voronoi <- function(data, tp, test.dim, Xlim, Ylim){ res.g <- f.create.grid(cbind(Xlim, Ylim), test.dim) xp <- res.g[[1]] yp <- res.g[[2]] zp <- res.g[[3]] numb.classes <- length(levels(factor(tp))) # Display classes as text plot(data[,1], data[,2], type="n", xlab="X", ylab = "Y", xlim=Xlim,ylim=Ylim) text(data[,1], data[,2], as.character(tp)) # Compute the nearest neighbour for the test points (grid) Z <- knn(data, zp, tp, k = 1) # For all cases in which the nn is 0 the contour map has a 1 else 0 # Draw the contour at 0.5 (add=T means add to current plot). for (c in 1:numb.classes) { contour(xp, yp, matrix(as.numeric(Z==(c-1)), length(xp), length(yp)), add=T, levels=0.5, labex=0, col="blue") } } testVoronoi <- function() { x.data.size <- 200 y.data.size <- 200 pos <- matrix(c(-1,1,-1,-1,1,2,1,-1), 4, 2, byrow=T) class <- matrix(c(0,1,2,3), 4, byrow=TRUE) Voronoi (pos, class, c(x.data.size, y.data.size), c(-2,2),c(-2,2)) pos <- matrix(c(-1,1,-1,-1,1,2,1,-1,0,0), 5, 2, byrow=T) class <- matrix(c(0,1,2,3,4), 5, byrow=TRUE) Voronoi (pos, class, c(x.data.size, y.data.size), c(-2,2),c(-2,2)) pos <- matrix(c(-2,1,-1,-1,1,2,1,-1,0,0), 5, 2, byrow=T) class <- matrix(c(0,1,2,3,4), 5, byrow=TRUE) Voronoi (pos, class, c(x.data.size, y.data.size), c(-2,2),c(-2,2)) pos <- matrix(c(-2,1, -1,-1, 1,2, 1,-1, 0,0, .5,-.5, 1,.5), 7, 2, byrow=T) class <- matrix(c(0,1,2,3,4,5,6), 7, byrow=TRUE) Voronoi (pos, class, c(x.data.size, y.data.size), c(-2,2),c(-2,2)) }