Assigning labels to observations in PCA

14 views (last 30 days)
Hi all,
I have been writing some code which invokes the use of PCA, and I am having trouble trying to colour the points according to a set of labels which I have already defined. I have included my code below:
clc ; close all ; clear all ;
%Principle components
a = 1;
b = 3;
load('Data.mat');
load("label.mat");
vbls = {'V1','V2','V3','V4','V5','V6','V7'};
C=corr(Data,Data)
z = zscore(Data);
[coeff,score,latent,~,explained] = pca(z)
Xcentered = score*coeff';
biplot(coeff(:,a:b),'scores',score(:,a:b),'VarLabels',vbls,'ObsLabels',Label);
xlabel('Principle Component 1 (53.1%)');
ylabel('Principle Component 2 (22.8%)');
zlabel('Principle Component 3 (13.9%)');
When I run this code, I am greeted with the error message "'ObsLabels' value must be a character array, string array, or cell array of character vectors with one label for each row of the 'Scores' matrix." However, I have a label for each of the rows in the score matrix defined (see pic below).
How can I label my observation points? I Only need to assign a colour to each of the observation points based on their labels. Any help will be very much appreciated, as I'm quite new to using MATLAB and performing dimensionality reduction.

Answers (1)

Shree Charan
Shree Charan on 5 Apr 2023
I understand that the ‘Label’ array passed to the ‘ObsLabels’ parameter of the biplot function is of the type double. However, as highlighted in Biplot - MATLAB biplot (mathworks.com), the ‘ObsLabels’ parameter accepts arrays of type string or char.
It would be useful to share the contents of the ‘Label’ array (label.mat) to better understand why the labels are of type "double" and if they can be converted to strings.
  3 Comments
Shree Charan
Shree Charan on 5 Apr 2023
Edited: Shree Charan on 5 Apr 2023
Looking at Labels, I'm assuming they are years. You may convert the array to a string array using the string function.
LabelString = string(Label)
I'm attaching the top rows of both Label and LabelString for your reference.
You can use further use biplot as
biplot(coeff(:,a:b),'scores',score(:,a:b),'VarLabels',vbls,'ObsLabels',LabelString);
Stephen Sweeting
Stephen Sweeting on 5 Apr 2023
Smashing! All works now. Thank you very much for the help. :)

Sign in to comment.

Categories

Find more on Dimensionality Reduction and Feature Extraction in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!