I have a KNN model that I draw using a function contour. This is a simple example of what I'm doing (based on this Purdue exam ):
library(class)
library(nnet)
TrainC<-read.table("http://miner.chem.purdue.edu/Exam1/TrainC.dat")
names(TrainC)<-c("x1","x2","y")
K=15
p <- as.matrix(TrainC[, -3])
xp <- seq(min(TrainC$x1), max(TrainC$x1), length = 50); np <- length(xp)
yp <- seq(min(TrainC$x2), max(TrainC$x2), length = 50)
tp<-TrainC$y
yhat <- knn(p, p, tp, k = K)
plot(TrainC[, 1], TrainC[, 2], xlab = "x1", ylab = "x2", col=as.numeric(TrainC$y)+1)
pt <- expand.grid(x1 = xp, x2 = yp)
Z <- knn(p, pt, tp, k = K)
zp<-class.ind(Z)[,1] - class.ind(Z)[,2]
contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0)
My question is: how can I make the same plot in ggplot? In particular, how can I make an equivalent contour?
source
share