Create LDA 2D and 3D plots

9 views (last 30 days)
Emily Pendleton
Emily Pendleton on 12 Oct 2018
Commented: James Richard on 17 Dec 2019
Hello, I'm trying to perform Linear Discriminate Analysis (LDA) on 2 groups with 88 variables describing the groups. I would like to plot my data along with the line used to discriminate groups. The code below only allows me to plot the line, but not the points of the group. I am thinking this is similar to the 'score' output of PCA, but I can't find the analogous variable for this output. Please help!
MdlLinear = fitcdiscr(data,categories)
K = MdlLinear.Coeffs(1,2).Const;
L = MdlLinear.Coeffs(2,1).Linear;
f = @(x1,x2) K + L(1)*x1 + L(2)*x2;
figure %create 2D plot
di2 = ezplot(f)
figure %create 3D plot
d13 = fsurf(f)
  2 Comments
Mor Guetta
Mor Guetta on 15 Jan 2019
What I did was first plotting the data and using the 'hold on' function adding the line.
I'm new to this so there probably is a better way, but this works just fine.
figure()
scatter(x1,y1); % 1st group
hold on
scatter(x2,y2); % 2nd group
hold on
d = ezplot(f); % LDA margin
James Richard
James Richard on 17 Dec 2019
You could try to use gscatter function instead instead, to make it easier.
gscatter(x1,x2,class,'rb','.',10,'on','x1','x2');
% plot x1 and x2 data which grouped by class
% x1 color is red
% x2 color is blue
% markers are dot with size of 10
% legend is on
% x1 label is x2
% x2 label is x2
hold on
fimplicit(f);
"ezplot is not recommended as it behaves differently under different environments"
Use fimplicit instead to plot it.
Btw, there is a fault on your code.
K = MdlLinear.Coeffs(1,2).Const;
L = MdlLinear.Coeffs(2,1).Linear;
It should be the same!
K = MdlLinear.Coeffs(1,2).Const;
L = MdlLinear.Coeffs(1,2).Linear;
% or
K = MdlLinear.Coeffs(2,1).Const;
L = MdlLinear.Coeffs(2,1).Linear;
It could result into wrong boundaries!
Try to debug it yourself in the Workspace Browser to see the difference.

Sign in to comment.

Answers (0)

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!