I would like to plot the decision boundaries of LDA for a matrix with 3 input variables and 2 classes. I could find some code for plotting the boundaries if only 2 input variables are given to LDA, but the code I found for 3 input variables gives an incorrect boundary.
# With 2 input variables
attach(iris)
index=Species!="versicolor"
iris=iris[index,]
LDA <- lda(Species ~ Sepal.Length + Sepal.Width, data=iris)
GS <- 500
x1 <- seq(min(Sepal.Length), max(Sepal.Length), len=GS)
x2 <- seq(min(Sepal.Width), max(Sepal.Width), len=GS)
x <- expand.grid(x1, x2)
newdat <- data.frame(Sepal.Length=x[,1], Sepal.Width=x[,2])
lda.Ghat <- as.numeric(predict(LDA, newdata=newdat)$class)
plot(Sepal.Length,Sepal.Width,col=Species)
contour(x1, x2, matrix(lda.Ghat, GS,GS),
levels=c(1,2),add=TRUE,drawlabels=FALSE, col="red")
legend("topright",legend=c('setosa','virginica'),fill=c("black","green"))
# With 3 input variables
LDA <- lda(Species ~ Sepal.Length + Sepal.Width + Petal.Length,data=iris)
GS <- 500
x1 <- seq(min(Sepal.Length), max(Sepal.Length), len=GS)
x2 <- seq(min(Sepal.Width), max(Sepal.Width), len=GS)
x <- expand.grid(x1, x2)
newdat <-data.frame(Sepal.Length=x[,1],Sepal.Width=x[,2],Petal.Length=mean(Petal.Length))
lda.Ghat <- as.numeric(predict(LDA, newdata=newdat)$class)
plot(Sepal.Length,Sepal.Width,col=Species)
contour(x1,x2,matrix(lda.Ghat,GS,GS),levels=c(1,2),add=TRUE,drawlabels=FALSE,col="red")
legend("topright",legend=c('setosa','virginica'),fill=c("black","green"))