How to put a legend automatically in PCA 3D Scatter Plot?
Show older comments
Here is my solution which successfully creates a 3D scatter plot, but I am unable to add legend to it. I will appreciate any help:
% data = mxn matrix; with all real numbers, no nan, inf or missing value.
% label = mx1 vector, e.g., label = [0;0;...;0;1;1;...;1;2;2;...;2;3;3;...;3]
myClrMap = [ 1 1 0; % Yellow
1 0 0; % Red
0 1 0; % Green
0 0 1; % Blue
];
[coeff_PCA, score_PCA, latent, tsquared, explained, mu] = pca(data);
h = figure();
subplot(1,2,1)
scatter3(score_PCA(:,1), score_PCA(:,2), score_PCA(:,3), 15, label, 'filled')
colormap(myClrMap)
class = unique(label);
% Below is my attempt to add legend which does not work.
[r, c] = size(myClrMap);
Legend = cell(r,1);
for i = 1:r
Legend{i} = strcat(length(class), num2str(i));
end
legend(Legend, 'location', 'best')
subplot(1,2,2)
...
...
...
2 Comments
Rik
on 24 Sep 2021
Original question:
How to put a legend automatically in PCA 3D Scatter Plot?
Here is my solution which successfully creates a 3D scatter plot, but I am unable to add legend to it. I will appreciate any help:
% data = mxn matrix; with all real numbers, no nan, inf or missing value.
% label = mx1 vector, e.g., label = [0;0;...;0;1;1;...;1;2;2;...;2;3;3;...;3]
myClrMap = [ 1 1 0; % Yellow
1 0 0; % Red
0 1 0; % Green
0 0 1; % Blue
];
[coeff_PCA, score_PCA, latent, tsquared, explained, mu] = pca(data);
h = figure();
subplot(1,2,1)
scatter3(score_PCA(:,1), score_PCA(:,2), score_PCA(:,3), 15, label, 'filled')
colormap(myClrMap)
class = unique(label);
% Below is my attempt to add legend which does not work.
[r, c] = size(myClrMap);
Legend = cell(r,1);
for i = 1:r
Legend{i} = strcat(length(class), num2str(i));
end
legend(Legend, 'location', 'best')
subplot(1,2,2)
...
...
...
Rena Berman
on 18 Oct 2021
(Answers Dev) Restored edit
Accepted Answer
More Answers (0)
Categories
Find more on Data Distribution Plots 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!