Phantom
Phantom

Reputation: 87

plot linear discriminant analysis in R

I would like to plot two matrices in scatter plot diagram. How can I do that? I like that this plot looks like ([this][1])

I'm calculating linear disciminant analysis on two classes with Fischer's method. This is what I calculate:

XM1 <- matrix(data=c(4,2, 2,4, 2,3, 3,6, 4,4), ncol = 2, byrow = TRUE)
XM2 <- matrix(data=c(9,10, 6,8, 9,5, 8,7, 10,8), ncol = 2, byrow = TRUE)
mi1 <- apply(XM1, MARGIN = 2, FUN = "mean")
mi2 <- apply(XM2, MARGIN = 2, FUN = "mean")
Sb <- (mi1-mi2)%*%t(mi1-mi2)
sum.cov <- (cov(XM1)+cov(XM2)) 
SwSb <- solve(sum.cov)%*%Sb
eg <- eigen(SwSb)

How do I plot these two matrices (one with circles, second with squares) with abline (using eigenval result)?

Upvotes: 1

Views: 2703

Answers (1)

Beasterfield
Beasterfield

Reputation: 7113

Here is a ggplot2 solution. First you have to bring your data in a appropriate form:

mdf <- as.data.frame( rbind(XM1, XM2) )
names(mdf) <- c("x1", "x2")
mdf$f <- c( rep( "a", nrow(XM1) ), rep( "b", nrow(XM2) ) )
head(mdf)
  x1 x2 f
1  4  2 a
2  2  4 a
3  2  3 a
4  3  6 a
5  4  4 a
6  9 10 b

And than this produces a plot similar to the one you showed:

library(ggplot2)
ggplot( mdf, aes(x=x1, y=x2, col=f) ) +
  geom_point( size = 4, aes(shape = f) ) +
  geom_abline( slope = eg$vectors[2,1] / eg$vectors[1,1], colour = "green"  ) +
  scale_shape_manual(values=c(16,15)) +
  expand_limits( y = 0, x = 0) +
  labs( title = paste("LDA projection vector with highest eigen value =", round(eg$values[1], 2)) ) +
  theme_bw() 

enter image description here

Upvotes: 3

Related Questions