Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contour of KNN model in ggplot?

Tags:

r

ggplot2

knn

I have a KNN model which I am plotting using the contour function. This is a simple example of the kind of thing that 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 this same plot in ggplot? In particular, how I can I do the equivalent of contour?

like image 761
griffin Avatar asked Dec 29 '22 02:12

griffin


2 Answers

d <- transform(melt(matrix(zp, np)), xp=xp[X1], yp=yp[X2])
ggplot(d, aes(xp, yp, z=value)) + 
  geom_contour() + 
  geom_point(aes(x1, x2, colour=y, z=NULL), data=TrainC)
like image 189
kohske Avatar answered Dec 30 '22 15:12

kohske


After your code try this:

library(ggplot2)

p <- ggplot(TrainC, aes(x1, x2))
p + geom_point(aes(colour = as.numeric(y) + 1))

df <- data.frame(x = rep(xp, np), y = rep(yp, each = np), z = zp)
p <- ggplot(df, aes(x, y, z = z))
p + stat_contour(bins = 1)

That's two separate plots. Not sure how to combine them but digging in the documentation here should get you started.

like image 26
J. Win. Avatar answered Dec 30 '22 14:12

J. Win.