PCA Calculator
Paste comma-separated numbers for each variable or upload a CSV, then get a complete principal component analysis: eigenvalues, explained variance, component loadings, communalities, component scores, varimax rotation, KMO and Bartlett checks, a scree plot and a biplot.
⚡ 0. Quick Answer
PCA, principal component analysis, turns many correlated variables into a few uncorrelated ones called principal components, ordered so the first one carries the most variance.
You standardise the variables, build their correlation matrix, and take its eigenvalues and eigenvectors. Each eigenvalue is the variance carried by one component. Divide an eigenvalue by the number of variables and you get the share of total information that component holds. Components with an eigenvalue above 1 are usually the ones worth keeping. PCA does not test a hypothesis and returns no p-value: it re-describes your data in fewer dimensions.
Rule of thumb: keep every component with an eigenvalue above 1.0, aim for a cumulative variance of at least 70%, and only name a component from variables that load above 0.40 on it. In the worked example on this page four exam subjects reduce to two components that together explain 94.72% of the variance.
Key takeaways
- A PCA calculator converts p correlated variables into p uncorrelated components, then lets you keep only the first few.
- Each eigenvalue is the variance held by one component, and the eigenvalues always sum to p when you use the correlation matrix.
- The Kaiser rule keeps components with an eigenvalue above 1.0, because below that a component explains less than a single original variable.
- Loadings are correlations between a variable and a component, so anything above 0.40 in absolute size is worth reading and anything above 0.70 defines the component.
- Use the correlation matrix whenever your variables have different units, otherwise the variable with the biggest numbers will hijack component one.
- PCA is descriptive, so it produces no p-value. The only significance test on this page, Bartlett's, checks that the variables are correlated enough to be worth reducing.
📚 1. What Is Principal Component Analysis?
Principal component analysis is a dimensionality-reduction technique that transforms correlated variables into a smaller set of uncorrelated variables, called principal components, that capture the maximum possible variance. It was set out by Pearson in 1901 and given its modern algebraic form by Hotelling in 1933.
Picture your data as a cloud of points in space, one axis per variable. If two variables are correlated, the cloud is a stretched cigar shape rather than a ball. PCA finds the long axis of that cigar and calls it component one. It then finds the longest direction at right angles to it and calls that component two, and so on. Nothing is thrown away at this stage: p variables give p components. The reduction happens when you decide the last few components hold so little variance that you can drop them.
What the calculator gives you:
- Eigenvalues, the variance carried by each component. On a correlation matrix they sum to the number of variables.
- Explained variance, each eigenvalue as a percentage, plus the running cumulative percentage.
- Loadings, the correlation between each original variable and each component. These are what you interpret.
- Communalities, how much of each variable is captured by the components you kept.
- Component scores, a new value for every case on every component, ready to paste into a regression or a cluster analysis.
- Eigenvectors, the weights the calculator used to build each score from the standardised data.
- Varimax rotation, an optional rotation that pushes each loading toward 0 or 1 so the components are easier to name.
- KMO and Bartlett's test, the two standard checks that your data are suitable for PCA at all.
A worked one-liner: twelve students sit four exams. Maths and Physics correlate at r = 0.90, English and History correlate at r = 0.89, and the two pairs barely relate to each other. PCA returns eigenvalues of 2.368 and 1.421, which is 59.20% and 35.51% of the variance. Two components replace four subjects and keep 94.72% of the information.
Who uses it and for what: psychologists reduce long questionnaires to a handful of underlying scales. Ecologists compress dozens of environmental measurements into two axes they can plot. Finance uses PCA on a yield curve, where the first three components are read as level, slope and curvature. Genomics uses it on expression matrices to see population structure. Image compression and face recognition, the eigenfaces method, are PCA applied to pixels. In machine learning it is the standard way to fight multicollinearity and shrink a feature set before fitting a model.
PCA against its nearest neighbour. The question people ask most is factor analysis vs principal components. They look alike and answer different questions.
| Question | PCA | Exploratory factor analysis |
|---|---|---|
| Goal | Re-describe total variance in fewer dimensions | Explain the shared variance with hidden latent factors |
| Model direction | Components are built from the variables | Factors are assumed to cause the variables |
| Diagonal of the matrix | 1.0, all variance is analysed | Estimated communalities, unique variance is removed |
| Error term | None, the solution is exact algebra | Yes, each variable has a unique error |
| Result is unique | Yes, up to the sign of each component | No, an infinite family of rotations fits equally well |
| Use it when | You want fewer variables to feed into another analysis | You believe in an underlying construct such as anxiety or ability |
| Typical fields | Ecology, chemometrics, finance, machine learning | Psychometrics, scale development, education |
In practice, when communalities are high and you have more than about 20 variables, PCA and factor analysis give nearly the same loadings. The difference matters most with few variables and modest correlations, which is exactly the situation in the worked example above.
🧮 2. Set Up Your Data
Each variable is one comma-separated list. Every list must hold the same number of observations, because one position in every list is one case. PCA needs at least three variables and works best when you have at least five cases per variable.
Type one value per cell. Each column becomes one variable and each row one case. Empty cells make that whole row unusable, so PCA drops the row.
📊 3. Results
🧠 4. Interpretation of Results, In Detail
4.1 Read the eigenvalues before anything else
An eigenvalue is the amount of variance one component carries. When you analyse the correlation matrix, every original variable has been standardised to a variance of exactly 1, so the eigenvalues sum to the number of variables. That single fact makes the whole table readable. With four variables the eigenvalues add to 4. A component with an eigenvalue of 2.4 is doing the work of 2.4 original variables. A component with an eigenvalue of 0.11 is doing almost nothing.
Divide any eigenvalue by the number of variables and you get the percentage of variance that component explains. This is the number you will quote in a paper. The cumulative column matters more than any single row, because it answers the only question a reader really has: how much of my data survives if I keep just these components.
Eigenvalues are always reported in descending order, and they always will be, because that is how PCA is defined. A rising eigenvalue further down the table is a sign the software failed, not a discovery.
4.2 How many components should you actually keep?
There is no single correct answer, which is why this calculator gives you four rules and shows you all of them at once.
- The Kaiser rule keeps components with an eigenvalue above 1.0. The logic is simple: on a correlation matrix a component below 1 explains less than one original variable, so keeping it is a step backwards. It is the default in SPSS and the most commonly reported rule. Its weakness is that it over-extracts when you have many variables, often keeping a third of them.
- The scree test asks you to look at plot 1 and find the elbow, the point where the curve flattens into scree. Keep the components above the elbow. It is subjective, but with a clear structure it is usually obvious and it usually beats Kaiser.
- The cumulative variance rule keeps components until you reach a target, commonly 70% or 80%. This is the rule to use when PCA is a pre-processing step and you care about how much information you are willing to lose.
- The broken-stick model compares each eigenvalue with what you would expect if the total variance were split at random. It is the strictest of the four and the least likely to over-extract, which is why ecologists favour it.
When the rules disagree, and they often do, prefer the interpretable solution. A three-component answer where every component has a name beats a four-component answer with an uninterpretable fourth. State in your write-up which rule you used and why, because a reviewer who cannot tell will assume you picked the flattering one.
4.3 What a loading actually is
A loading is the correlation between an original variable and a component. It runs from minus 1 to plus 1 and is read exactly like any other correlation. A loading of 0.85 means that variable moves almost in lockstep with the component. A loading of minus 0.85 is just as strong, in the opposite direction.
The conventional cut-offs are 0.30 for a loading worth mentioning, 0.40 for one worth interpreting, and 0.70 for one that defines the component. Some fields use 0.32, following Tabachnick and Fidell, because 0.32 squared is roughly 10% shared variance. The exact threshold matters less than applying the same one to the whole table and saying which you used.
Do not confuse loadings with eigenvector weights. The eigenvector is the recipe used to build the score; the loading is the correlation you interpret. On a correlation matrix loading equals eigenvector times the square root of the eigenvalue, which is why they look similar but never match.
4.4 Naming your components
This is the part software cannot do for you. Take one component, list every variable loading above 0.40 on it, look at what those variables have in common, and give it a short name. Then check the variables loading negatively, because they belong to the same component pointing the other way.
In the worked example, Maths and Physics load one way on component one while English and History load the other way. That component is not "maths ability", it is a quantitative versus verbal contrast, and naming it as a contrast is the honest reading. Component two has all four variables loading positively at a similar size, which is the classic signature of a general "overall performance" component.
Two warnings. A component you cannot name is usually a component you should not keep. And a name is a hypothesis, not a finding, so write "component one was interpreted as" rather than "component one measured".
4.5 The sign of a component is arbitrary
If you multiply an eigenvector by minus 1 it is still an eigenvector of the same matrix with the same eigenvalue. Nothing in the mathematics fixes the direction. That is why the same data can give loadings of plus 0.77 in R and minus 0.77 in Python, and neither is wrong.
This calculator uses the convention that the largest loading on each component is made positive, which is what scikit-learn does. R's prcomp applies no convention at all and returns whatever the underlying decomposition produced. If your signs flip between software, the interpretation flips with them and the conclusion is unchanged. Never treat a sign difference as a discrepancy, and never report one without saying which direction you called positive.
4.6 Communalities tell you which variables belong
A communality is the sum of squared loadings for one variable across the components you kept. It is the share of that variable explained by the retained solution, and it runs from 0 to 1.
High communalities, above about 0.60, mean the retained components represent that variable well. A communality below 0.40 is a warning: that variable is largely independent of everything else, and keeping it in the analysis does nothing except dilute the components. The usual response is to drop it and rerun, then say so in the methods.
Uniqueness is simply 1 minus communality. Some software reports one, some the other, and they carry identical information.
4.7 Correlation matrix or covariance matrix?
This choice changes the answer more than any other setting on the page, and it is the mistake beginners make most often.
The covariance matrix uses the raw variances. If one variable is measured in millimetres and another in kilometres, the millimetre variable has a numerically enormous variance and will dominate component one entirely. The result is arithmetically correct and scientifically useless.
The correlation matrix standardises every variable to a variance of 1 first, so each one enters the analysis on equal terms. This is the right default and it is what almost every published PCA uses. Choose covariance only when all variables share a unit and the differences in their spread are part of what you want the analysis to see, for example repeated measurements of the same quantity or a set of log-transformed variables.
4.8 Rotation, and why it does not cheat
An unrotated solution spreads variance so component one grabs as much as possible. That is optimal mathematically and often terrible for interpretation, because many variables load moderately on component one and nothing defines anything.
Varimax rotation turns the retained components as a rigid frame, pushing each loading toward either 0 or 1 while keeping the components uncorrelated. The total variance explained by the retained set does not change by a single decimal place, only its distribution across components changes. Nothing is manufactured.
Rotate when you have kept two or more components and want to name them. Do not rotate when PCA is a pre-processing step feeding a regression or a clustering, because then the ordering by variance is the point. And never rotate a one-component solution: there is nothing to rotate against.
One honest warning about software. Varimax is an iterative search, not a closed-form calculation, so different programs can land on different rotations of the same solution. This calculator sweeps every pair of retained components repeatedly until the varimax criterion stops improving. R's varimax() starts from the identity matrix and on small problems, four variables and two components in particular, it can stop at a local optimum with a visibly less simple structure. Both answers preserve the total variance and every communality exactly, so neither is wrong in the sense of being miscalculated, but they are not the same rotation. If you are comparing this page with R and the rotated loadings differ, compare the simplicity of the two tables rather than assuming one is broken.
4.9 KMO and Bartlett, the two entry checks
The Kaiser-Meyer-Olkin measure asks whether your correlations are widespread or scattered. It compares ordinary correlations with partial correlations. If variables share common factors, partial correlations are small and KMO approaches 1. Kaiser's own labels: below 0.50 unacceptable, 0.50 to 0.59 miserable, 0.60 to 0.69 mediocre, 0.70 to 0.79 middling, 0.80 to 0.89 meritorious, above 0.90 marvellous. KMO is unreliable with very few variables and is not worth reporting below about six.
Bartlett's test of sphericity tests whether the correlation matrix is an identity matrix, meaning no variable correlates with any other. A significant result, p below 0.05, says the correlations are strong enough to be worth reducing. It is a low bar and it is almost always significant with a decent sample, so a non-significant Bartlett is a genuine red flag and a significant one is not evidence of much.
4.10 Sample size: how much is enough?
The old guidance was a fixed ratio, five or ten cases per variable, or an absolute floor of 100 or 300 cases. Those rules are simple and they are not very good.
The modern position, following MacCallum and colleagues, is that the required sample depends on the communalities. When communalities are high, above 0.60, even 60 cases can give a stable solution. When they hover around 0.50 you want 100 to 200. When they are low and you have few variables per component, you may need 500 and still get an unstable answer. Report your n and your communalities together and let the reader judge.
A separate hard limit applies whatever the guidance says. If you have fewer cases than variables, the correlation matrix is singular, some eigenvalues are exactly 0, and the last components are meaningless noise. The calculator warns you when this happens.
4.11 What PCA cannot tell you
PCA has no p-value for the components themselves, no confidence intervals as standard, and no significance test, because it is a description of the data and not an inference about a population. It cannot tell you that a component is real.
It finds linear structure only. Data lying on a curved manifold, a horseshoe or a ring, will be badly represented by straight axes, and the components can produce the arch effect that ecologists know well. It is not robust to outliers: one extreme case can define a whole component on its own, which is why robust principal component analysis exists.
It also gives you no causal claim whatsoever. A component is a weighted sum of what you measured. If you did not measure it, PCA cannot find it.
4.12 Practical judgement, in order
Check suitability first: KMO, Bartlett, sample size, and a scan of the correlation matrix for a variable that correlates with nothing. Then decide the number of components using the scree plot and one stated rule, not four rules chosen after the fact. Then rotate if you are naming components. Then read the loadings and write the names down before you look at anything else, so you are not fitting the story to a later result.
Finally, sanity-check the communalities. If every variable is well represented and the components have names you would defend out loud, the analysis is done. If one variable will not fit anywhere, drop it, rerun, and report both solutions.
✍ 5. How to Write Your Results in Research
▶ Run the analysis above to auto-fill all five examples with your own results.
5.1 What a complete PCA write-up must contain
Reviewers reject principal component analysis sections for a small, predictable list of omissions. Include all nine of these and the section will pass.
- The number of variables entered and the number of cases, with any exclusions.
- Whether you analysed the correlation or the covariance matrix, and why.
- The suitability evidence: KMO, Bartlett's test with its chi-square, degrees of freedom and p-value.
- The rule you used to decide how many components to keep, stated before the result.
- Eigenvalues and the percentage of variance for every retained component, plus the cumulative percentage.
- The loading table, with the cut-off you applied and whether small loadings were suppressed.
- The rotation used, or a clear statement that none was used.
- Your interpretation and name for each component.
- The software and version. This calculator's citation is in Section 19.
5.2 Five ready-to-use templates
📌 Key conventions for this style
- APA italicises p, n and M but not KMO.
- Report exact p-values to three decimals unless below .001, then write p < .001.
- APA drops the leading zero for anything that cannot exceed 1, so write .87 not 0.87 for a loading or a p-value.
- Percentages of variance take two decimal places.
- The loading table goes in the Results section, not an appendix, unless there are more than about 20 variables.
📌 Key conventions for this style
- State the retention rule before the number of components, not after, so it does not look chosen to fit.
- Give the determinant of the correlation matrix if you discuss multicollinearity; below 0.00001 is a problem.
- Report communalities in the same table as the loadings.
- If you dropped a variable after a first run, report both runs.
- Name the software and version in the Methods chapter, not the Results.
📌 Key conventions for this style
- Never write eigenvalue, loading, orthogonal or variance in a plain-language summary.
- "Summary score" is the clearest everyday substitute for component.
- Say what the score means in the reader's terms, for example "a general fitness score".
- Give the retained percentage as a whole number.
- Say plainly what was lost, not only what was kept.
📌 Key conventions for this style
- Abstracts have no room for a loading table, so give the component names instead.
- Keep the number of decimal places identical across every figure quoted.
- Posters should show the scree plot rather than the eigenvalue table; it reads from three metres away.
- Declare the rotation even when there was none. "Unrotated" is information.
- Put n in the Methods line, never only in a figure caption.
📌 Key conventions for this style
- Fix the retention rule, the rotation and the loading threshold before you see the data. These three are where analytic flexibility hides.
- State the exact variable list; adding one variable changes every loading.
- Commit in advance to what you will do about a low communality or a singular matrix.
- Say how missing data will be handled, listwise or by imputation.
- Deposit the raw correlation matrix so others can reproduce the eigenvalues exactly.
5.3 Table and figure conventions
The loading table is the centrepiece. Put variables in rows and components in columns, sort rows by their highest loading so the block structure is visible, and suppress loadings below your stated threshold. Add a communality column on the right and an eigenvalue and percentage-of-variance row at the bottom. Give the table a note stating the extraction method, the rotation and the suppression threshold.
The scree plot is the figure. Plot component number on the x axis and eigenvalue on the y axis, draw a horizontal reference line at 1.0, and mark the retained components. A biplot is a good second figure when you have a two-component solution and want to show cases and variables together, but it becomes unreadable above about 200 cases.
5.4 The Discussion sentence
Link each component back to your research question, not to the algebra. Write "the quantitative-verbal contrast explained most of the variation between students, which supports the two-domain view of attainment" rather than "component one had an eigenvalue of 2.368". The eigenvalue belongs in Results. The meaning belongs in Discussion.
5.5 Reporting checklist
- n and p stated, with exclusions.
- Correlation or covariance matrix named.
- KMO and Bartlett reported with chi-square, df and p.
- Retention rule stated before the result.
- Eigenvalues and percentage variance for every retained component.
- Cumulative variance given.
- Loading table with a stated threshold.
- Communalities reported.
- Rotation named, including "none".
- Each component interpreted and named.
- Software and version cited.
- Scree plot included.
∑ 6. Formulas Used
Seven formulas take you from raw data to a named component. They run in this order, and every number this calculator prints comes from one of them.
📝 7. How to Use This PCA Calculator
Ten steps, start to finish. The worked example used throughout this page is four exam subjects measured on twelve students.
- Load or paste your data. Pick a sample dataset from the dropdown, or paste one comma-separated list of numbers into each variable box. Spaces, tabs and new lines work as separators too.
- Name each variable. The group name box at the top of every variable is editable. Type the real name, for example
Maths, so the loading table reads properly instead of showing Variable 1. - Add every variable you want reduced. Press Add variable until they are all on the page. PCA needs at least three, and there is no upper limit here beyond your patience.
- Check the counts match. Each box shows how many numbers it holds. Every variable must hold the same count, because position 1 in each list is the same case. The calculator refuses to run when they differ.
- Or upload a file instead. On the Upload tab choose a CSV or Excel file, then click the column names you want. Every column you click becomes its own variable. Press Load selected columns as variables to send them into the calculator.
- Choose correlation or covariance. Leave it on correlation unless every variable shares one unit. This is the setting that changes the answer most.
- Choose a retention rule. Kaiser, 80% cumulative variance, broken stick, or a fixed number. Decide before you look at the answer, and say which you used when you write it up.
- Press Run PCA. Nothing is computed until you do. The results, the four plots and the reporting sentences all appear together.
- Read the loadings and name the components. Green cells are strong loadings, yellow are moderate. Give each retained component a short name from the variables that define it. Turn on varimax rotation if the picture is muddy.
- Export. Download Doc gives a plain text report, Download PDF opens the print dialog with a clean A4 layout, and the copy buttons in Section 5 put a finished sentence on your clipboard.
Worked example: paste 52, 48, 55, 61, 47, 70, 66, 58, 44, 63, 57, 50 into variable 1, name it Maths, then add Physics, English and History from the sample dataset. Run it. You should see eigenvalues of 2.3681 and 1.4206, which is 59.20% and 35.51% of the variance and 94.72% cumulative.
📈 8. How to Calculate PCA in Excel
Excel can do a complete principal component analysis, but it will not hand you one. There is no =PCA() function and the Analysis ToolPak has no PCA entry, so you have to build the eigenvalues yourself. The good news is that the two hard steps, the correlation matrix and the matrix multiplication, both have direct functions, and the eigenvalues fall out of a short iteration you can drag down a column.
=CORREL(), then repeat =MMULT(R, v) on a starting vector and rescale it each time. The vector settles on the first eigenvector and the length it settles at is the first eigenvalue.8.1 The functions you need
| You want | Excel function | Note |
|---|---|---|
| Mean of a variable | =AVERAGE(A2:A13) | Needed for the z-scores |
| Sample standard deviation | =STDEV.S(A2:A13) | Divisor n − 1. STDEV.P gives a different answer |
| Standardise a value | =STANDARDIZE(A2,$A$16,$A$17) | Or just =(A2-$A$16)/$A$17 |
| One correlation | =CORREL(A2:A13,B2:B13) | Mix absolute and relative refs so it fills across the block |
| The whole correlation matrix | Data → Data Analysis → Correlation | Analysis ToolPak. Fills only the lower triangle, so mirror it yourself |
| Matrix multiply | =MMULT(range1,range2) | Array formula. In Excel 2019 or older press Ctrl+Shift+Enter |
| Vector length | =SQRT(SUMSQ(range)) | Used to rescale the vector each iteration |
| Matrix determinant | =MDETERM(G2:J5) | The determinant of R, needed for Bartlett's test |
| Matrix inverse | =MINVERSE(G2:J5) | Needed only if you want KMO |
| Transpose a block | =TRANSPOSE(range) | Turns a row vector into a column vector for MMULT |
| Bartlett p-value | =CHISQ.DIST.RT(chi2,df) | df is p(p − 1)/2, which is 6 for four variables |
| Sum of squares | =SUMSQ(W2:X2) | Squared loadings across kept components gives the communality |
STDEV.P divides by n and STDEV.S divides by n − 1. Correlations are unaffected because the divisor cancels, but your z-scores and therefore your component scores will be wrong by a factor of √(n/(n−1)) if you pick the wrong one. This calculator, R and Python all use the n − 1 version.8.2 Step by step
1 Lay the data out, one variable per column
Put each variable in its own column with a real name in row 1. Every row is one case, so row 2 is student 1 across all four subjects. This is the layout every statistics program expects, and it is the layout the upload tab on this page reads.
A1:D13 12 cases, 4 variablesTwelve students, four subjects. The first seven rows are shown. Student 1 scored 52 in Maths, 59 in Physics, 70 in English and 72 in History.
2 Build the correlation matrix
In cell G2 type the formula below and fill it right and down across a four by four block. The mixed reference style, $A$2:$A$13 against B$2:B$13, is what makes one formula fill the whole matrix. The diagonal will come out as exactly 1.
Maths and Physics correlate at 0.8958, English and History at 0.8926, and every cross-pair sits near −0.23. That block pattern is what PCA is about to turn into two components.
3 Find the first eigenvalue by power iteration
Start with any vector that is not all zeros, for example 0.5, 0.5, −0.5, −0.5. Multiply it by the correlation matrix, measure the length of the result, then divide the result by that length. Repeat. The vector stops moving after about five rows and the length it settles on is the largest eigenvalue.
=MMULT($G$2:$J$5,TRANSPOSE(G7:J7)) =SQRT(SUMSQ(...))The length converges to 2.368096 by iteration 5 and stops changing. That is λ1 = 2.3681, and the settled vector 0.5006, 0.5012, −0.4951, −0.5031 is the first eigenvector.
4 Deflate the matrix and repeat for the rest
Subtract the first component from the matrix, using R2 = R − λ1 v1 v1′, then run exactly the same power iteration on R2. That gives the second eigenvalue. Repeat until you have all four. Then divide each eigenvalue by 4, the number of variables, to get the percentage of variance.
Four eigenvalues: 2.3681, 1.4206, 0.1105, 0.1008. They sum to exactly 4, the number of variables. Two clear the Kaiser line of 1, and together they hold 94.72% of the variance.
5 Turn eigenvectors into loadings
A loading is the eigenvector element multiplied by the square root of its eigenvalue. Square the loadings across the components you kept and add them to get the communality for that variable. One minus the communality is the uniqueness.
=L8*SQRT($P$8) =SUMSQ(W2:X2) =1-Y2Maths and Physics load at about −0.77 on PC1 while English and History load at about +0.77: that is the quantitative versus verbal contrast. All four communalities exceed 0.94, so two components represent every subject well.
6 Compute the component scores
Standardise the raw data first, then multiply the z-score matrix by the eigenvector matrix. One MMULT over the whole block gives every case a score on every component. Those scores are what you paste into a regression.
Student 1 scores 0.7865 on PC1 and 0.3056 on PC2. Student 3, who scored 55 in every subject, sits at −1.1567 on PC1 and −1.7641 on PC2, which marks them as low on the general performance component.
8.3 The awkward cases
There is no eigenvalue function. This is the only genuinely hard part. Power iteration with MMULT works and is what step 3 shows, but it is slow to set up for more than about six variables and it needs deflation for each extra component. For a serious analysis with many variables, install a free add-in that has PCA built in, or move the job to R or Python. Do not try to solve the characteristic polynomial by hand above three variables.
MMULT is an array formula. In Microsoft 365 it spills automatically. In Excel 2019 and earlier you must select the whole output range first, type the formula, then press Ctrl+Shift+Enter. If you press plain Enter you get one number instead of a matrix and nothing downstream works.
The ToolPak correlation output is triangular. Data Analysis → Correlation fills only the lower triangle and leaves the upper half blank. MMULT needs a full square matrix, so mirror the values across the diagonal before you use it, or build the matrix with CORREL as in step 2.
KMO needs a matrix inverse. Use =MINVERSE(G2:J5), then convert to partial correlations with −ajk ÷ √(ajj akk). It is doable but fiddly, and Excel will refuse if the matrix is singular. If your determinant from =MDETERM() is close to zero, the inverse is unreliable and KMO cannot be trusted.
Rotation is not practical in Excel. Varimax is an iterative procedure over pairs of components. Nobody should build it in a spreadsheet. Use the rotation dropdown on this page, or R's varimax().
8.4 Why your Excel answer might differ from R or Python
| Situation | What happens | Fix |
|---|---|---|
| Signs are flipped | Power iteration lands on whichever direction its starting vector was closest to, so a whole column comes out negated. R, Python and Excel routinely disagree here | Not an error. Multiply the column by −1 so the largest weight is positive, and say which direction you called positive |
| Blank cells in a column | CORREL silently drops the pair, so different correlations are built on different numbers of cases and the matrix can stop being positive definite | Delete incomplete rows before you start, so every correlation uses the same n |
STDEV.P used instead of STDEV.S | Z-scores are too large by √(n/(n−1)), so component scores are inflated. Loadings are unaffected | Always STDEV.S for sample data. It matches R's sd() and NumPy's ddof=1 |
| Numbers stored as text | CORREL skips them, so n silently shrinks and the correlation changes | Select the column, Data → Text to Columns → Finish, then check the count with =COUNT() |
| Power iteration stopped early | The eigenvalue is close but not converged, so it disagrees in the third decimal | Drag another ten rows down. It costs nothing and the value stops moving |
| You analysed covariances, they analysed correlations | Completely different eigenvalues that no longer sum to p | Decide once and state it. R's prcomp needs scale.=TRUE for the correlation matrix, and it is FALSE by default |
| Rounded values retyped between steps | Error compounds through the iteration and the last eigenvalue can be visibly wrong | Reference cells rather than retyping. Change display decimals, never the stored value |
8.5 Charting the result in Excel
Select the eigenvalue column with its component labels, then Insert → Line with Markers. That is your scree plot. Two formatting changes make it publication ready: set the y-axis minimum to 0 so the drop is not exaggerated, and add a horizontal line at 1.0 by plotting a second series of 1s and formatting it as a dashed grey line. Label it "Kaiser criterion" so a reader knows what it is.
For a loading plot, select the PC1 and PC2 loading columns and insert a Scatter chart, then add data labels from the variable name column using the "Value From Cells" option. Set both axes to run from −1 to 1 and add axis lines through zero, because a loading plot is only readable when the origin is visible.
8.6 Excel errors you will probably hit
| Error | Cause | Fix |
|---|---|---|
#VALUE! from MMULT | The inner dimensions do not match, or a cell in the range holds text | Columns of the first block must equal rows of the second. Transpose one of them |
#N/A spilling across the block | Array formula entered with plain Enter in an older Excel | Select the output range, retype, press Ctrl+Shift+Enter |
#DIV/0! from CORREL | One variable has zero variance because every value is identical | Drop that variable. A constant carries no information for PCA |
#NUM! from MINVERSE | The correlation matrix is singular, usually because two variables are perfectly correlated or n is less than p | Remove one of the duplicated variables, or collect more cases |
#SPILL! | Something is already sitting in the cells the array wants to fill | Clear the block below and to the right of the formula cell |
#REF! after a delete | A row or column the formula pointed at was removed | Undo, then use whole-range names so edits do not break references |
📈 9. How to Calculate PCA in R
R gives you principal component analysis in one line with prcomp(dat, scale. = TRUE), and that one line is almost never what you should report. It returns standard deviations rather than eigenvalues, no loadings in the correlation sense, no communalities and no suitability checks. The script below does the full job in base R with no packages at all, so it runs on any installation.
Rscript pca_script.R. The only line you need to change is the data.frame at the top, or swap in the commented read.csv() line just below it. It prints a full summary and saves pca_plot.png at 300 dpi.All three ship with R. Nothing to install. eigen(), cor() and pchisq() live in stats, and png() lives in grDevices.
9.1 The complete script
# ===================================================================== # Principal Component Analysis (PCA) in R, base R only # Worked example: 12 students, 4 exam subjects # Saves pca_plot.png at 300 dpi. Run with: Rscript pca_script.R # ===================================================================== set.seed(42) # reproducible, so the figure is identical every run # ---- 1. YOUR DATA. Change only this block. -------------------------- dat <- data.frame( Maths = c(52, 48, 55, 61, 47, 70, 66, 58, 44, 63, 57, 50), Physics = c(59, 42, 54, 60, 49, 71, 70, 68, 48, 71, 64, 51), English = c(70, 81, 55, 79, 71, 61, 59, 77, 67, 71, 60, 61), History = c(72, 79, 55, 72, 68, 57, 64, 72, 61, 69, 56, 65) ) # From a file instead: # dat <- read.csv("exam_scores.csv") # dat <- dat[complete.cases(dat), ] # drop any row with a missing value n <- nrow(dat); p <- ncol(dat) # ---- 2. Correlation matrix and eigen-decomposition ------------------ R <- cor(dat) eg <- eigen(R) # eigen() returns values already sorted, largest first evals <- eg$values evecs <- eg$vectors # Sign convention: make the largest weight in each column positive. # R applies no convention of its own, so without this your signs may # differ from Python, SPSS or this page. The interpretation is identical. for (k in seq_len(p)) { j <- which.max(abs(evecs[, k])) if (evecs[j, k] < 0) evecs[, k] <- -evecs[, k] } rownames(evecs) <- names(dat) colnames(evecs) <- paste0("PC", seq_len(p)) prop <- 100 * evals / sum(evals) cum <- cumsum(prop) loadings <- evecs %*% diag(sqrt(evals)) # loading = eigenvector * sqrt(eigenvalue) dimnames(loadings) <- dimnames(evecs) Z <- scale(dat) # scale() uses sd(), divisor n - 1 scores <- Z %*% evecs keep <- max(sum(evals > 1), 1) # Kaiser rule comm <- rowSums(loadings[, seq_len(keep), drop = FALSE]^2) # ---- 3. Suitability checks ------------------------------------------ detR <- det(R) bart <- -((n - 1) - (2 * p + 5) / 6) * log(detR) df <- p * (p - 1) / 2 bart_p <- pchisq(bart, df, lower.tail = FALSE) Rinv <- solve(R) D <- diag(1 / sqrt(diag(Rinv))) partial <- -D %*% Rinv %*% D diag(partial) <- 0 Roff <- R; diag(Roff) <- 0 kmo <- sum(Roff^2) / (sum(Roff^2) + sum(partial^2)) # ---- 4. Printed summary --------------------------------------------- cat("PRINCIPAL COMPONENT ANALYSIS\n") cat(sprintf("Cases n = %d Variables p = %d Matrix: correlation\n\n", n, p)) cat("Eigenvalues and variance explained\n") print(round(data.frame(Eigenvalue = evals, Percent = prop, Cumulative = cum, row.names = colnames(evecs)), 4)) cat("\nLoadings and communality\n") print(round(cbind(loadings[, seq_len(keep), drop = FALSE], h2 = comm), 4)) cat("\nSuitability\n") cat(sprintf(" KMO = %.4f\n", kmo)) cat(sprintf(" Bartlett chi2(%d) = %.4f, p = %.3g\n", df, bart, bart_p)) cat(sprintf(" Determinant of R = %.6f\n", detR)) cat(sprintf("\nVERDICT: Bartlett is significant and KMO is %.2f, so the variables are correlated enough for PCA. Keeping %d component(s) retains %.2f%% of the variance.\n", kmo, keep, cum[keep])) # ---- 5. One 300 dpi figure: scree plot + biplot ---------------------- png("pca_plot.png", width = 11, height = 4.6, units = "in", res = 300) par(mfrow = c(1, 2), mar = c(4.4, 4.4, 3, 1.4)) plot(seq_len(p), evals, type = "b", pch = 19, cex = 1.4, lwd = 2.2, col = "#16a34a", xlab = "Component", ylab = "Eigenvalue", main = "Scree plot", ylim = c(0, max(evals) * 1.2), xaxt = "n") axis(1, at = seq_len(p)) abline(h = 1, lty = 2, col = "#9ca3af", lwd = 1.4) text(p, 1.08, "Kaiser criterion", adj = 1, cex = .8, col = "#6b7280") grid(col = "#e5e7eb") sc <- max(abs(scores[, 1:2])) / max(abs(loadings[, 1:2])) * 0.85 plot(scores[, 1], scores[, 2], pch = 19, col = "#2563eb", cex = 1.2, xlab = sprintf("PC1 (%.2f%%)", prop[1]), ylab = sprintf("PC2 (%.2f%%)", prop[2]), main = "Biplot: cases and variables") abline(h = 0, v = 0, col = "#d1d5db") grid(col = "#e5e7eb") arrows(0, 0, loadings[, 1] * sc, loadings[, 2] * sc, col = "#c2410c", lwd = 2, length = .1) text(loadings[, 1] * sc * 1.14, loadings[, 2] * sc * 1.14, rownames(loadings), col = "#7c2d12", font = 2, cex = .9) mtext(sprintf("Principal Component Analysis, n = %d, p = %d", n, p), outer = TRUE, line = -1.4, font = 2) dev.off() cat("\nFigure saved to pca_plot.png at 300 dpi\n")
9.2 What each part does
| Line or function | What it does and why it is there |
|---|---|
cor(dat) | Builds the correlation matrix. Use cov(dat) instead if every variable shares a unit and you deliberately want covariance PCA. |
eigen(R) | Returns eigenvalues in $values, already sorted largest first, and eigenvectors as the columns of $vectors. No sorting step is needed, unlike in NumPy. |
| The sign loop | R applies no sign convention at all, so eigen() can return a column and its negative on different machines. This loop forces the largest weight positive, which matches scikit-learn and this page. |
evecs %*% diag(sqrt(evals)) | Converts eigenvectors into loadings. Skipping this is the most common R mistake: prcomp()$rotation holds eigenvectors, not loadings, despite the name. |
scale(dat) | Z-scores every column using sd(), which divides by n − 1. This matches Excel's STDEV.S and NumPy's ddof=1. |
sum(evals > 1) | The Kaiser rule as one expression. Change it to which(cumsum(prop) >= 80)[1] for the 80% variance rule. |
rowSums(loadings[, 1:keep]^2) | Communalities. The drop = FALSE argument matters: without it a one-component solution collapses the matrix to a vector and rowSums fails. |
det(R) and pchisq() | Bartlett's test of sphericity. lower.tail = FALSE gives the upper-tail p-value, which is the one you want. |
solve(R) | Inverts the correlation matrix for the KMO calculation. It throws an error on a singular matrix, which is itself a useful warning that two variables are redundant. |
png(..., res = 300) | Opens a 300 dpi device. Every plot call after it writes into the file until dev.off() closes it. Forgetting dev.off() leaves an empty or locked file. |
set.seed(42) | Not needed for the PCA itself, which is deterministic, but it keeps any jitter or resampling you add later reproducible. |
prcomp() defaults to scale. = FALSE, which means the covariance matrix. SPSS, SAS and most textbooks default to the correlation matrix. If your R answer does not match a published one, this is the first thing to check.9.3 What the figure shows
The left panel is the scree plot. Eigenvalues fall from 2.37 to 1.42, then collapse to about 0.11. The dashed line at 1.0 is the Kaiser criterion, and the elbow sits clearly between components 2 and 3, so both rules agree on a two-component solution.
The right panel is the biplot. Blue points are the twelve students positioned by their PC1 and PC2 scores. Orange arrows are the four subjects, drawn from the origin with their length set by their loadings. Maths and Physics point one way, English and History the other, and the near-90-degree angle between the two pairs is the picture of two independent components. A student sitting far along an arrow scored highly on that subject.
9.4 Common R problems and fixes
| Problem | Cause | Fix |
|---|---|---|
| Loadings do not match SPSS | prcomp()$rotation holds eigenvectors, not loadings | Multiply by sqrt(eigenvalue), as the script does |
| Everything loads on one component | scale. = FALSE, so one high-variance variable dominates | Use scale. = TRUE, or cor() as in this script |
| Rotated loadings differ from this page | varimax() starts from the identity matrix and can stop at a local optimum when p and k are both small | Not a bug in either tool. Compare the varimax criterion, or start varimax() from a random orthogonal matrix and keep the simplest result |
| Signs differ from a colleague's run | No sign convention in eigen() | Keep the sign loop. It is three lines and it removes the whole problem |
NA everywhere in cor() | Missing values in the data frame | dat[complete.cases(dat), ], or cor(dat, use = "complete.obs") |
Error in solve.default(R): system is computationally singular | Two variables are perfectly or near-perfectly correlated, or n is smaller than p | Drop one of them, or collect more cases. Check det(R) first |
A factor column breaks cor() | A character or factor column crept into the data frame | dat <- dat[sapply(dat, is.numeric)] |
| Empty or corrupt PNG | dev.off() not reached because an error stopped the script | Run dev.off() manually, then rerun from the top |
rowSums fails on a one-component solution | Single-column subsetting dropped the matrix to a vector | Add drop = FALSE when subsetting |
9.5 Useful one-liners
# The fast version, correlation matrix PCA p1 <- prcomp(dat, scale. = TRUE); summary(p1) # Eigenvalues from prcomp: square the standard deviations p1$sdev^2 # Loadings, the way SPSS reports them p1$rotation %*% diag(p1$sdev) # Varimax rotation on the first two components varimax(p1$rotation[, 1:2] %*% diag(p1$sdev[1:2])) # Component scores for every case head(p1$x) # Scree plot in one call screeplot(p1, type = "lines", main = "Scree plot") # Built-in biplot biplot(p1, cex = 0.8) # Write the loadings to CSV write.csv(round(loadings, 4), "pca_loadings.csv")
📈 10. How to Calculate PCA in Python
Most people reach for sklearn.decomposition.PCA, and for a machine-learning pipeline that is the right choice. For a paper it is the wrong shape: scikit-learn gives you explained_variance_ratio_ and components_, but no loadings, no communalities, no KMO and no Bartlett test. The script below uses NumPy and SciPy directly so every number a reviewer asks for is printed.
pca_script.py and run python pca_script.py, or paste it into a Jupyter cell. The only line you need to change is the X = np.array(...) block, or swap in the commented pd.read_csv() line. It prints a full summary and saves pca_plot.png at 300 dpi.Install with pip install numpy scipy matplotlib pandas. NumPy does the eigen-decomposition, SciPy supplies the chi-square distribution for Bartlett's test, matplotlib draws the figure, and pandas is needed only if you read a CSV.
10.1 The complete script
# ===================================================================== # Principal Component Analysis (PCA) in Python # Worked example: 12 students, 4 exam subjects # Saves pca_plot.png at 300 dpi. Run with: python pca_script.py # ===================================================================== import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from scipy.stats import chi2 np.random.seed(42) # reproducible jitter in the biplot # ---- 1. YOUR DATA. Change only this block. -------------------------- labels = ["Maths", "Physics", "English", "History"] X = np.array([ [52, 59, 70, 72], [48, 42, 81, 79], [55, 54, 55, 55], [61, 60, 79, 72], [47, 49, 71, 68], [70, 71, 61, 57], [66, 70, 59, 64], [58, 68, 77, 72], [44, 48, 67, 61], [63, 71, 71, 69], [57, 64, 60, 56], [50, 51, 61, 65], ], dtype=float) # From a file instead: # import pandas as pd # df = pd.read_csv("exam_scores.csv").dropna() # drop rows with any missing value # labels, X = list(df.columns), df.to_numpy(dtype=float) n, p = X.shape # ---- 2. Standardise, then build the correlation matrix -------------- Z = (X - X.mean(axis=0)) / X.std(axis=0, ddof=1) # ddof=1 matches R's sd() R = np.corrcoef(X, rowvar=False) # ---- 3. Eigen-decomposition ---------------------------------------- evals, evecs = np.linalg.eigh(R) # eigh: R is symmetric order = np.argsort(evals)[::-1] # largest eigenvalue first evals, evecs = evals[order], evecs[:, order] for k in range(p): # sign convention: biggest weight positive j = np.argmax(np.abs(evecs[:, k])) if evecs[j, k] < 0: evecs[:, k] *= -1 prop = 100 * evals / evals.sum() cum = np.cumsum(prop) loadings = evecs * np.sqrt(evals) # loading = eigenvector * sqrt(eigenvalue) scores = Z @ evecs # one score per case per component keep = int((evals > 1).sum()) # Kaiser rule keep = max(keep, 1) comm = (loadings[:, :keep] ** 2).sum(axis=1) # communality over kept components # ---- 4. Suitability checks ----------------------------------------- detR = np.linalg.det(R) bart = -((n - 1) - (2 * p + 5) / 6) * np.log(detR) df = p * (p - 1) / 2 bart_p = chi2.sf(bart, df) Rinv = np.linalg.inv(R) D = np.diag(1 / np.sqrt(np.diag(Rinv))) partial = -D @ Rinv @ D np.fill_diagonal(partial, 0) Roff = R.copy() np.fill_diagonal(Roff, 0) kmo = (Roff ** 2).sum() / ((Roff ** 2).sum() + (partial ** 2).sum()) # ---- 5. Printed summary -------------------------------------------- print("PRINCIPAL COMPONENT ANALYSIS") print("Cases n = %d Variables p = %d Matrix: correlation" % (n, p)) print("\nEigenvalues and variance explained") print("%-6s %12s %12s %12s" % ("PC", "Eigenvalue", "% variance", "Cumulative %")) for k in range(p): print("%-6s %12.4f %12.2f %12.2f" % ("PC%d" % (k + 1), evals[k], prop[k], cum[k])) print("\nLoadings (first %d components) and communality" % keep) head = "%-10s" % "Variable" + "".join("%10s" % ("PC%d" % (k + 1)) for k in range(keep)) + "%12s" % "h2" print(head) for j in range(p): row = "%-10s" % labels[j] + "".join("%10.4f" % loadings[j, k] for k in range(keep)) print(row + "%12.4f" % comm[j]) print("\nSuitability") print(" KMO = %.4f" % kmo) print(" Bartlett chi2(%d) = %.4f, p = %.3g" % (df, bart, bart_p)) print(" Determinant of R = %.6f" % detR) verdict = ("Bartlett is significant and KMO is %.2f, so the variables are correlated enough for PCA. " "Keeping %d component%s retains %.2f%% of the variance." % (kmo, keep, "" if keep == 1 else "s", cum[keep - 1])) print("\nVERDICT: " + verdict) # ---- 6. One 300 dpi figure: scree plot + biplot --------------------- fig, ax = plt.subplots(1, 2, figsize=(11, 4.6)) ax[0].plot(range(1, p + 1), evals, "o-", color="#16a34a", lw=2.2, ms=8) ax[0].axhline(1, ls="--", color="#9ca3af", lw=1.4) ax[0].text(p, 1.06, "Kaiser criterion", ha="right", fontsize=9, color="#6b7280") ax[0].set_xticks(range(1, p + 1)) ax[0].set_xlabel("Component"); ax[0].set_ylabel("Eigenvalue") ax[0].set_title("Scree plot"); ax[0].set_ylim(0, max(evals) * 1.2) ax[0].grid(alpha=.3) ax[1].axhline(0, color="#d1d5db", lw=1); ax[1].axvline(0, color="#d1d5db", lw=1) ax[1].scatter(scores[:, 0], scores[:, 1], s=46, color="#2563eb", alpha=.75, zorder=3) scale = np.abs(scores[:, :2]).max() / np.abs(loadings[:, :2]).max() * 0.85 for j in range(p): ax[1].arrow(0, 0, loadings[j, 0] * scale, loadings[j, 1] * scale, color="#c2410c", width=.012, head_width=.11, length_includes_head=True, zorder=4) ax[1].text(loadings[j, 0] * scale * 1.14, loadings[j, 1] * scale * 1.14, labels[j], color="#7c2d12", fontsize=9.5, fontweight="bold", ha="center") ax[1].set_xlabel("PC1 (%.2f%%)" % prop[0]); ax[1].set_ylabel("PC2 (%.2f%%)" % prop[1]) ax[1].set_title("Biplot: cases and variables"); ax[1].grid(alpha=.3) fig.suptitle("Principal Component Analysis, n = %d, p = %d" % (n, p), fontweight="bold") fig.tight_layout() fig.savefig("pca_plot.png", dpi=300, bbox_inches="tight") print("\nFigure saved to pca_plot.png at 300 dpi")
10.2 What each part does
| Line or function | What it does and why it is there |
|---|---|
np.corrcoef(X, rowvar=False) | Builds the correlation matrix. The rowvar=False argument is essential: without it NumPy treats rows as variables and you get an n by n matrix of the wrong thing. |
np.linalg.eigh(R) | Eigen-decomposition for a symmetric matrix. Use eigh, not eig: eig is for general matrices and can return tiny imaginary parts that break everything downstream. |
np.argsort(evals)[::-1] | eigh returns eigenvalues in ascending order, the opposite of R. Skipping this sort is the single most common NumPy PCA bug. |
| The sign loop | Forces the largest weight in each eigenvector positive. This is what scikit-learn's svd_flip does internally, so the script agrees with sklearn out of the box. |
X.std(axis=0, ddof=1) | ddof=1 gives the sample standard deviation. NumPy defaults to ddof=0, the population version, which does not match R's sd() or Excel's STDEV.S. |
evecs * np.sqrt(evals) | Broadcasts the square-root eigenvalues across the columns to give loadings. Because evals is a row of length p and evecs is p by p, this multiplies column k by sqrt(evals[k]), which is exactly what is wanted. |
Z @ evecs | Matrix multiplication for the component scores. Use @, never *, which does elementwise multiplication and fails silently on square matrices. |
chi2.sf(bart, df) | The survival function, which is the upper-tail p-value. Using chi2.cdf gives one minus the answer you want. |
np.linalg.inv(R) | Inverts R for the KMO calculation. Prefer np.linalg.pinv if you expect a singular matrix, but a singular matrix is a reason to fix the data, not to work around it. |
np.fill_diagonal(partial, 0) | KMO sums only off-diagonal terms. Leaving the diagonal in inflates both sums and gives a KMO that is always near 0.5. |
matplotlib.use("Agg") | Selects a non-interactive backend so the script runs on a server with no display. Drop this line and add plt.show() in Jupyter. |
np.nanmean if you have gaps | np.mean returns nan if any value is nan. For PCA, though, drop incomplete rows entirely rather than averaging around them, so every correlation uses the same cases. |
sklearn.decomposition.PCA centres the data but does not scale it. Feeding it raw columns gives covariance PCA, so one large-variance variable takes over component one. Wrap it in a pipeline with StandardScaler(), or standardise first as this script does.10.3 What the figure shows
The same two panels as the R figure, and by design the same numbers. The scree plot on the left drops steeply from 2.37 to 1.42 and then flattens near 0.11, which is a textbook elbow. The biplot on the right places the twelve students by their PC1 and PC2 scores in blue and draws the four subject loadings as orange arrows.
Read the biplot by angle. Two arrows pointing the same way are positively correlated variables. Two arrows at right angles are uncorrelated. Two arrows pointing opposite ways are negatively correlated. Here Maths and Physics sit almost on top of each other, English and History sit almost on top of each other, and the two pairs point in opposite directions along PC1.
10.4 Common Python problems and fixes
| Problem | Cause | Fix |
|---|---|---|
| Eigenvalues come out in the wrong order | np.linalg.eigh returns them ascending | Sort descending with np.argsort(evals)[::-1] and reorder the eigenvectors with the same index |
| Complex numbers appear | np.linalg.eig used on a symmetric matrix | Use np.linalg.eigh, which is both faster and guaranteed real |
| Scores disagree with R by a constant factor | ddof=0 left as the default in .std() | Set ddof=1 everywhere you compute a standard deviation |
| Correlation matrix is n by n | rowvar left at its default of True | Pass rowvar=False, or transpose the array first |
| sklearn gives different loadings | components_ holds eigenvectors as rows, not loadings, and they need transposing too | loadings = pca.components_.T * np.sqrt(pca.explained_variance_) |
| One variable dominates PC1 entirely | Data were not standardised, so covariance PCA ran | Standardise first, or use a StandardScaler pipeline |
LinAlgError: Singular matrix | Perfect collinearity or fewer cases than variables | Drop a redundant variable, or use np.linalg.pinv knowing the KMO becomes unreliable |
| Blank figure file | plt.show() called before savefig, which clears the canvas | Always save first, then show |
| Arrows invisible on the biplot | Loadings are on a scale of ±1 while scores run to ±3 | Multiply the loadings by a scale factor, as the script does |
10.5 Useful one-liners
# The fast version with scikit-learn, standardised from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler Z = StandardScaler().fit_transform(X); fit = PCA().fit(Z) # Eigenvalues and percentage of variance fit.explained_variance_; fit.explained_variance_ratio_ * 100 # Loadings the way SPSS reports them fit.components_.T * np.sqrt(fit.explained_variance_) # Keep only enough components for 80 percent of the variance PCA(n_components=0.80).fit_transform(Z) # Component scores for every case fit.transform(Z)[:5] # Varimax rotation using factor_analyzer from factor_analyzer.rotator import Rotator Rotator(method="varimax").fit_transform(loadings[:, :2]) # KMO and Bartlett in one import from factor_analyzer.factor_analyzer import calculate_kmo, calculate_bartlett_sphericity # Save the loadings to CSV import pandas as pd; pd.DataFrame(loadings, index=labels).round(4).to_csv("pca_loadings.csv")
Run it with python pca_script.py from a terminal. In Jupyter, delete the matplotlib.use("Agg") line and add plt.show() at the end so the figure appears inline as well as on disk.
📋 11. Reference Tables
Eight lookup tables covering every threshold this calculator applies. Each one says what to conclude, not only what the number is.
11.1 The four component retention rules compared
| Rule | Keep a component when | Tends to | Best used when |
|---|---|---|---|
| Kaiser criterion | Eigenvalue > 1.00 | Over-extract, badly above 30 variables | You need the conventional, expected answer |
| Scree test | It sits above the elbow of the curve | Be accurate but subjective | The elbow is visibly sharp |
| Cumulative variance | Running total is below 70% or 80% | Vary with the target you pick | PCA is a pre-processing step |
| Broken stick | Eigenvalue > the random expectation in 11.5 | Under-extract, the strictest rule | Ecology, or when false components are costly |
| Parallel analysis | Eigenvalue beats the 95th percentile from random data | Be the most accurate of all | You have software that simulates it, such as R's psych::fa.parallel |
What to conclude: when the rules disagree, report the one you chose in advance and mention the alternative in a sentence. Parallel analysis is the most accurate in simulation studies (Zwick and Velicer, 1986) but Kaiser remains the most widely reported.
11.2 Interpreting the size of a loading
| |Loading| | Shared variance | Label | What to do |
|---|---|---|---|
| 0.71 and above | 50% or more | Excellent | This variable defines the component. Use it for the name |
| 0.63 to 0.70 | 40% to 49% | Very good | Include it in the interpretation |
| 0.55 to 0.62 | 30% to 39% | Good | Include it, mention it second |
| 0.45 to 0.54 | 20% to 29% | Fair | Report it, interpret with care |
| 0.32 to 0.44 | 10% to 19% | Poor | The usual minimum to report at all |
| Below 0.32 | Under 10% | Ignore | Suppress it in the table |
What to conclude: these bands follow Comrey and Lee (1992) and the 0.32 floor follows Tabachnick and Fidell. A variable loading above 0.32 on two or more components is cross-loading, and the usual response is to drop it or to rotate.
11.3 Kaiser-Meyer-Olkin sampling adequacy
| KMO | Kaiser's label | Verdict |
|---|---|---|
| 0.90 to 1.00 | Marvellous | Ideal for PCA |
| 0.80 to 0.89 | Meritorious | Proceed with confidence |
| 0.70 to 0.79 | Middling | Proceed |
| 0.60 to 0.69 | Mediocre | Acceptable, the usual published floor |
| 0.50 to 0.59 | Miserable | Marginal. Consider dropping weak variables |
| Below 0.50 | Unacceptable | Do not proceed. Collect more variables or more cases |
What to conclude: KMO is unstable with fewer than about six variables, because there are too few partial correlations to average over. With four variables a KMO near 0.50 is normal and is not by itself a reason to abandon the analysis. Check the per-variable MSA values too: a single variable below 0.50 is a candidate for removal.
11.4 How many cases do you need?
| Guidance | Requirement | Source and status |
|---|---|---|
| Cases per variable | 5 minimum, 10 preferred, 20 comfortable | Traditional rule of thumb. Simple, widely quoted, weakly supported |
| Absolute n | 100 poor, 200 fair, 300 good, 500 very good, 1000 excellent | Comrey and Lee (1992). Still the most cited table |
| High communalities, above 0.60 | n of 60 can be enough | MacCallum et al. (1999). The modern position |
| Moderate communalities, near 0.50 | n of 100 to 200 | MacCallum et al. (1999) |
| Low communalities, below 0.40 | n of 500 or more, and expect instability | MacCallum et al. (1999) |
| Hard limit | n must exceed p | Algebraic. Below it the matrix is singular and the last eigenvalues are exactly zero |
What to conclude: report n, p and your communalities together. A small n with high communalities and few components is far safer than a large n with poor communalities. The old ratio rules are a starting point, not a standard.
11.5 Broken-stick expected eigenvalues
| Variables p | PC1 | PC2 | PC3 | PC4 | PC5 | PC6 |
|---|---|---|---|---|---|---|
| 3 | 1.833 | 0.833 | 0.333 | - | - | - |
| 4 | 2.083 | 1.083 | 0.583 | 0.250 | - | - |
| 5 | 2.283 | 1.283 | 0.783 | 0.450 | 0.200 | - |
| 6 | 2.450 | 1.450 | 0.950 | 0.617 | 0.367 | 0.167 |
| 7 | 2.593 | 1.593 | 1.093 | 0.760 | 0.510 | 0.310 |
| 8 | 2.718 | 1.718 | 1.218 | 0.885 | 0.635 | 0.435 |
| 9 | 2.829 | 1.829 | 1.329 | 0.996 | 0.746 | 0.546 |
| 10 | 2.929 | 1.929 | 1.429 | 1.096 | 0.846 | 0.646 |
What to conclude: keep component k only while its observed eigenvalue exceeds the value in this table, and stop at the first component that fails. In the worked example, p = 4 and the observed eigenvalues 2.3681 and 1.4206 both beat 2.083 and 1.083, so the broken-stick rule also keeps two components. Values are the expected lengths of pieces of a randomly broken unit stick, rescaled to p.
11.6 Cumulative variance targets by field
| Field | Typical target | Why |
|---|---|---|
| Psychometrics and questionnaire work | 50% to 60% | Items are noisy, so a lower share is normal and accepted |
| Social sciences generally | 60% | The conventional floor for a reportable solution |
| Ecology and environmental data | 70% to 80% | Measurements are physical and strongly correlated |
| Chemometrics and spectroscopy | 95% or more | Adjacent wavelengths are almost redundant |
| Machine learning pre-processing | 90% to 99% | Set by how much information loss the model can absorb |
| Image compression | Whatever the eye accepts | Judged visually, not statistically |
What to conclude: a cumulative variance that looks low in one field is normal in another. State your target before you extract, and never move it after seeing the answer.
11.7 Chi-square critical values for Bartlett's test
| Variables p | df = p(p−1)/2 | α = .05 | α = .01 | α = .001 |
|---|---|---|---|---|
| 3 | 3 | 7.815 | 11.345 | 16.266 |
| 4 | 6 | 12.592 | 16.812 | 22.458 |
| 5 | 10 | 18.307 | 23.209 | 29.588 |
| 6 | 15 | 24.996 | 30.578 | 37.697 |
| 7 | 21 | 32.671 | 38.932 | 46.797 |
| 8 | 28 | 41.337 | 48.278 | 56.892 |
| 9 | 36 | 50.998 | 58.619 | 67.985 |
| 10 | 45 | 61.656 | 69.957 | 80.077 |
| 11 | 55 | 73.311 | 82.292 | 93.168 |
| 12 | 66 | 85.965 | 95.626 | 107.258 |
What to conclude: if your Bartlett chi-square exceeds the .05 column, the correlation matrix differs significantly from an identity matrix and PCA is worth running. In the worked example, chi-square(6) = 29.008 beats even the .001 value of 22.458. Note that with a large n this test is significant almost automatically, so passing it is a floor, not a recommendation.
11.8 PCA against the methods people confuse it with
| Method | What it does differently | Use it instead when |
|---|---|---|
| Exploratory factor analysis | Models shared variance only and assumes latent causes | You believe in an underlying construct such as anxiety |
| Confirmatory factor analysis | Tests a structure you specify in advance, with fit indices | You already have a hypothesised factor structure |
| Linear discriminant analysis | Maximises separation between known groups, not total variance | You have labelled groups and want to classify |
| Robust PCA | Splits the data into a low-rank part and a sparse outlier part | A few extreme cases are distorting the components |
| Probabilistic PCA | Adds an explicit noise model, so it handles missing data | You need likelihoods, confidence intervals, or have gaps in the data |
| Kernel PCA | Finds non-linear structure via a kernel function | The data lie on a curved surface and linear axes fail |
| Principal component regression | Regresses an outcome on the retained component scores | Predictors are heavily multicollinear |
| Correspondence analysis | The categorical equivalent, based on chi-square distance | Your data are counts in a contingency table |
| t-SNE and UMAP | Non-linear methods built for visualisation only | You want a 2D picture and do not need interpretable axes |
What to conclude: PCA is the default first move for numeric, roughly linear data. Move to one of the alternatives only when you can name the specific assumption PCA is breaking.
📈 12. Example Results
Eight worked analyses, every number computed with the same engine that runs above. They span the range on purpose: a clean textbook case, a single dominant component, a borderline eigenvalue, no structure at all, a sample that is too small, a component the Kaiser rule would wrongly discard, a matrix broken by a duplicated variable, and a field study where rotation rescues the interpretation.
Exam scores: the textbook two-component case
TextbookTwelve students sat four exams: Maths, Physics, English and History. The question is whether attainment is one thing or two.
| Component | Eigenvalue | % variance | Cumulative % | Kept |
|---|---|---|---|---|
| PC1 | 2.3681 | 59.20 | 59.20 | Yes |
| PC2 | 1.4206 | 35.51 | 94.72 | Yes |
| PC3 | 0.1105 | 2.76 | 97.48 | No |
| PC4 | 0.1008 | 2.52 | 100.00 | No |
What it means: two components replace four subjects and keep 94.72% of the information. PC1 has Maths and Physics at about −0.77 against English and History at about +0.77, which is a quantitative versus verbal contrast. PC2 has all four loading positively near +0.59, which is general attainment. Every communality exceeds 0.94.
How to write it: "Two components with eigenvalues above 1 explained 94.72% of the variance. PC1 (59.20%) contrasted quantitative with verbal subjects; PC2 (35.51%) represented general attainment."
Body measurements: one component takes almost everything
Clear resultHeight, weight, chest circumference, foot length and BMI measured on twenty adults. Every measurement is driven by overall body size.
| Variable | PC1 loading | Communality |
|---|---|---|
| Height | 0.993 | 0.986 |
| Weight | 0.992 | 0.984 |
| Chest | 0.991 | 0.982 |
| Foot length | 0.981 | 0.962 |
| BMI | 0.987 | 0.974 |
What it means: all five loadings exceed 0.98 on one component, and eigenvalues 2 to 5 are all below 0.07. This is a general size factor. There is nothing to rotate, because rotation needs two or more components to rotate against.
How to write it: "A single component with an eigenvalue of 4.89 explained 97.80% of the variance; all five measurements loaded above .98 and the component was interpreted as overall body size."
Borderline: an eigenvalue sitting exactly on 1.00
BorderlineFive questionnaire items from forty respondents. Three items hang together, one stands slightly apart, and the second eigenvalue lands at 1.0008.
| Component | Eigenvalue | % variance | Cumulative % | Kaiser | Broken stick (p = 5) |
|---|---|---|---|---|---|
| PC1 | 3.0116 | 60.23 | 60.23 | Keep | Keep, beats 2.283 |
| PC2 | 1.0008 | 20.02 | 80.25 | Keep, just | Drop, misses 1.283 |
| PC3 | 0.6362 | 12.72 | 92.97 | Drop | Drop |
What it means: Kaiser keeps two components, broken stick keeps one. The tie-breaker is interpretability: item 4 loads 0.939 on PC2 and only −0.235 on PC1, so PC2 is carrying real, distinct content and is worth keeping. Never resolve a borderline case by picking the rule that gives the answer you wanted.
How to write it: "The second component fell marginally above Kaiser's criterion (λ = 1.00, 20.02% of variance). It was retained because item 4 loaded .94 on it and .24 or below elsewhere, giving it a clear interpretation."
No structure at all: PCA has nothing to reduce
Null resultFour variables measured on fifty cases with no real relationship between any of them. This is what a failed PCA looks like, and it is a result worth recognising.
| Check | Value | Verdict |
|---|---|---|
| Eigenvalues | 1.229, 1.161, 0.878, 0.732 | All near 1, no dominant component |
| Cumulative variance, 2 components | 59.75% | Barely better than the 50% two variables give free |
| Determinant of R | 0.917 | Close to 1, so R is almost an identity matrix |
| Bartlett chi-square(6) | 4.057, p = .669 | Not significant. The correlations are indistinguishable from zero |
What it means: Bartlett's test failed, so the whole analysis should stop here. PCA still returns four components because the algebra always works, but they are noise. Two components explaining 59.75% of four variables is close to what pure chance gives.
How to write it: "Bartlett's test of sphericity was not significant, chi-square(6) = 4.06, p = .669, indicating the correlation matrix did not differ from an identity matrix. Principal component analysis was therefore not pursued."
Too few cases: a solution you cannot trust
Small sampleFive variables measured on only eight cases. The output looks respectable, and that is exactly the danger.
| Diagnostic | Value | Requirement | Verdict |
|---|---|---|---|
| Cases per variable | 1.6 | 5 minimum, 10 preferred | Fails badly |
| Absolute n | 8 | 100 is called "poor" | Fails |
| Cumulative variance, 2 PCs | 89.45% | Above 70% | Passes, but inflated by small n |
| Bartlett chi-square(10) | 30.08, p = .0008 | p below .05 | Passes, and means little here |
What it means: with fewer cases than five per variable the correlations themselves have huge standard errors, so the eigenvalues do too. Cumulative variance is systematically overstated when n is small. Adding two cases could change which variables define PC1.
How to write it: "With only 8 cases for 5 variables (1.6 per variable), the component solution should be treated as exploratory. Results are reported to guide a larger confirmatory study rather than as a stable structure."
When Kaiser throws away a real component
Rule failureFive survey items on sixty respondents. The second eigenvalue is 0.8645, so the Kaiser rule discards it, yet one item loads 0.895 on it and nowhere else.
| Item | PC1 loading | PC2 loading | Reading |
|---|---|---|---|
| Q1 | 0.931 | −0.165 | Defines PC1 |
| Q2 | 0.926 | −0.074 | Defines PC1 |
| Q3 | 0.443 | 0.895 | Belongs to PC2 |
| Q4 | 0.912 | −0.175 | Defines PC1 |
| Q5 | 0.947 | −0.016 | Defines PC1 |
What it means: the Kaiser rule is a rule of thumb, not a law. Here it would drop the only component that separates Q3 from the rest, and Q3's communality would fall from 0.997 to 0.196. The scree elbow, the loadings and the communalities all say keep two.
How to write it: "Although the second component fell marginally below Kaiser's criterion (λ = .86), it was retained on the basis of the scree plot and because item 3 loaded .90 on it, raising its communality from .20 to 1.00."
A duplicated variable makes the matrix singular
Assumption failureTemperature was recorded twice, once in the field notebook and once by a logger, and both columns went into the analysis. They correlate at 0.9999.
| Symptom | Value | What it tells you |
|---|---|---|
| Smallest eigenvalue | 0.0000 | An exact linear dependency exists between the variables |
| Determinant of R | 0.000001 | Below the 0.00001 warning threshold |
| Largest correlation | r = 0.9999 | Two columns are effectively the same variable |
| KMO | Cannot be computed | The matrix inverse does not exist |
What it means: PCA still returns eigenvalues, and PC1 still explains 80.24% of the variance, but the duplicate has silently doubled the weight of temperature in that component. Drop one of the two columns and rerun. The same thing happens with a total that is the sum of its parts, or a percentage and its complement both entered.
How to write it: "The determinant of the correlation matrix was below .00001, indicating extreme multicollinearity. One of two near-identical temperature measures was removed and the analysis rerun on the remaining three variables."
Water quality: rotation rescues the interpretation
Applied field studySix water-quality variables measured at twenty-four river sites. The unrotated solution had every variable loading on both components, so nothing could be named.
| Variable | Unrotated PC1 | Unrotated PC2 | Rotated RC1 | Rotated RC2 | Communality |
|---|---|---|---|---|---|
| pH | 0.758 | −0.611 | −0.972 | 0.061 | 0.948 |
| Dissolved oxygen | −0.787 | 0.585 | 0.976 | −0.098 | 0.962 |
| Conductivity | 0.808 | −0.557 | −0.972 | 0.134 | 0.962 |
| Nitrate | 0.676 | 0.710 | −0.020 | 0.980 | 0.962 |
| Turbidity | 0.778 | 0.576 | −0.185 | 0.950 | 0.937 |
| Phosphate | 0.711 | 0.626 | −0.102 | 0.942 | 0.897 |
| Sum of squared loadings | 3.413 | 2.254 | 2.886 | 2.781 | 5.667 |
What it means: rotation moved variance between the two components, 3.413 and 2.254 became 2.886 and 2.781, but the total is 5.667 before and after and every communality is identical to four decimal places. Nothing was created. The rotated components are readable as a mineralisation axis and a nutrient enrichment axis.
How to write it: "Two components explaining 94.45% of the variance were retained and rotated using varimax. RC1 (48.1% after rotation) loaded on pH, dissolved oxygen and conductivity and was interpreted as mineralisation; RC2 (46.4%) loaded on nitrate, turbidity and phosphate and was interpreted as nutrient enrichment."
🧪 13. Data Collection Protocol
Design this PCA calculator assumes: a single sample of independent cases, each measured on the same set of continuous or near-continuous numeric variables, with no missing values and no grouping structure. PCA has no groups, no treatment and no outcome. Every variable enters on the same footing.
13.1 Twelve steps to data a principal component analysis can use
- Define the case. Decide what one row is: a person, a site, a sample, a day. Every variable must be measurable on that same unit.
- Choose the variables before you collect. Adding one variable later changes every loading in the table, so the variable list is part of the design, not a decision made at analysis time.
- Aim for at least five cases per variable, and prefer ten. With 8 variables that means 40 minimum and 80 preferred. Section 11.4 gives the modern communality-based guidance.
- Keep every variable numeric and continuous. Binary and nominal variables break the correlation matrix that principal component analysis is built on. Use correspondence analysis or categorical PCA for those.
- Measure on a meaningful scale. Ordinal Likert items with five or more points are acceptable in practice and widely published, but three-point scales are not.
- Standardise the measurement procedure. The same instrument, the same observer, the same time of day. Measurement drift becomes a spurious component.
- Do not enter a variable and its own components. A total and its parts, or a percentage and its complement, create an exact linear dependency and a zero eigenvalue.
- Record raw values, never pre-standardised ones. The calculator standardises for you. Standardising twice is harmless for the correlation matrix but breaks the covariance option.
- Handle missing data before you start. Delete incomplete rows, or impute them explicitly and say so. Pairwise deletion builds different correlations from different case sets and can produce a matrix that is not positive definite.
- Screen for outliers first. One extreme case can define an entire component. Plot every variable before you run anything, and report any case you remove.
- Check for a constant variable. A column where every value is identical has zero variance and no correlation with anything. It must be removed.
- Pre-register the retention rule and the loading threshold. These two decisions are where analytic flexibility hides, so fix them before the data arrive.
13.2 The data layout the calculator expects
| Case ID | Maths | Physics | English | History |
|---|---|---|---|---|
| S001 | 52 | 59 | 70 | 72 |
| S002 | 48 | 42 | 81 | 79 |
| S003 | 55 | 54 | 55 | 55 |
One row per case, one column per variable, a header row of real variable names, and no ID column mixed into the numbers. On the Upload tab you click the four numeric columns you want and each becomes its own variable in the calculator. The case ID column is simply not clicked.
13.3 Minimum sample and pre-registration
The hard algebraic minimum is that the number of cases must exceed the number of variables, otherwise the correlation matrix is singular. The practical minimum for a stable solution is 5 cases per variable with an absolute floor around 50, and 10 per variable with a floor around 100 for anything you intend to publish.
Pre-register four things: the exact variable list, correlation or covariance, the retention rule, and the loading threshold for interpretation. Also state in advance what you will do if a communality falls below 0.40, because deciding that after seeing the result is where most PCA papers lose credibility.
13.4 Common mistakes that make data unusable for PCA
- Mixing units without standardising. Fixed by the correlation matrix default, but fatal if you switch to covariance without thinking.
- Entering a sum alongside its parts. Creates an exact dependency and a zero eigenvalue.
- Different numbers of observations per variable. Each row must be one case across every variable, so ragged columns cannot be analysed.
- Coding missing values as 0 or 999. These become real numbers and destroy the correlations. Leave them blank and delete the row.
- Including an ID or a date column as a variable. Case numbers correlate with collection order and produce a meaningless component.
- Analysing groups together that should be separate. Two populations mixed into one PCA produce a first component that just separates the groups.
🎯 14. When to Use This PCA Calculator
This free PCA calculator is designed for researchers, students and analysts who have several correlated numeric variables and want fewer of them without losing the information they carry.
14.1 Use it when
- You have three or more numeric variables measured on the same cases.
- The variables are correlated, and you suspect they measure overlapping things.
- You want a small number of scores to feed into a regression, a clustering, or a plot.
- You want to see the structure in a correlation matrix rather than read 45 correlations one by one.
- You need to fight multicollinearity before fitting a model.
- You want a two-dimensional picture of a many-dimensional dataset.
14.2 Do not use it when
- Your variables are categorical or binary. Use correspondence analysis or multiple correspondence analysis.
- You have fewer cases than variables. The matrix is singular and the answer is not defined.
- You want to test a specific factor structure. Use confirmatory factor analysis.
- You believe in a latent construct that causes the variables. Use exploratory factor analysis.
- You have known groups and want to separate them. Use linear discriminant analysis.
- The relationships are curved rather than linear. Use kernel PCA, or transform the variables first.
- Your variables are uncorrelated. Bartlett's test will tell you, and there is nothing to reduce.
14.3 Four real situations
| Situation | Variables | What PCA gives you |
|---|---|---|
| A 30-item wellbeing questionnaire | 30 Likert items | Three or four subscale scores instead of thirty item scores |
| River monitoring at 40 sites | pH, DO, nitrate, phosphate, turbidity, conductivity | Two axes, usually mineralisation and nutrient enrichment, that you can plot the sites on |
| Predicting house price with 20 collinear features | Area, rooms, age, distance measures | Six uncorrelated component scores that a regression can actually fit |
| Morphology of 200 beetles | 12 body measurements | A size component and one or two shape components |
14.4 Decision tree: is PCA the right tool?
- Are your variables numeric and continuous? No → correspondence analysis or categorical PCA. Yes → next.
- Do you have more cases than variables? No → stop, collect more cases or drop variables. Yes → next.
- Is Bartlett's test significant? No → stop, there is no shared structure to find. Yes → next.
- Do you want to model hidden causes, or just compress? Model causes → exploratory factor analysis. Compress → next.
- Do you have labelled groups you want to separate? Yes → linear discriminant analysis. No → next.
- Are the relationships roughly linear? No → kernel PCA, t-SNE or UMAP. Yes → PCA is the right tool. Run it above.
🔧 15. Troubleshooting and Common Errors
The calculator says my variables have different lengths
Cause: one variable has more or fewer numbers than another, usually a stray trailing comma or a missing value someone deleted.
Fix: the count under each box tells you how many numbers it holds. Make every count identical. If a case is genuinely missing a measurement, delete that position from every variable, because one row must be one case across the whole table.
Everything loads on the first component and nothing else matters
Cause: either you selected the covariance matrix while your variables have wildly different scales, or the variables really are all measuring one thing.
Fix: switch to the correlation matrix and rerun. If the picture is unchanged, you have a genuine general factor, which is a real and reportable finding. Body size, general ability and socioeconomic status all behave this way.
My loadings have the opposite sign to the published paper I am replicating
Cause: the sign of a component is mathematically arbitrary. An eigenvector and its negative are both valid.
Fix: nothing is wrong. Multiply the whole column by minus 1 if you want to match, and say in the write-up which direction you called positive. Never treat this as a discrepancy, and never flip only some of the loadings in a column.
One eigenvalue comes out as exactly zero
Cause: an exact linear dependency. A duplicated variable, a total entered alongside its parts, a percentage plus its complement, or fewer cases than variables.
Fix: find the dependency and remove one of the variables involved. Check the correlation matrix for a pair at r above 0.99 and the determinant, which will be near zero. Then rerun.
KMO comes out low, around 0.5, on a small variable set
Cause: KMO averages over partial correlations, and with only four or five variables there are too few of them for the average to be stable.
Fix: read the per-variable MSA values rather than the overall figure, and lean on Bartlett's test and the correlation matrix instead. Below about six variables, treat KMO as a hint, not a gate.
A variable has a communality below 0.40
Cause: that variable is largely independent of the others, so the retained components explain almost none of it.
Fix: remove it and rerun. Report both solutions and say why you dropped it. Keeping it does not help: it contributes noise to every component without being represented by any of them.
Two variables load about equally on two components
Cause: a cross-loading. The variable belongs to both components, or to neither cleanly.
Fix: try varimax rotation first, which is designed to fix exactly this. If the cross-loading survives rotation, the variable is genuinely ambiguous. Drop it, or accept it and say so explicitly in the results.
Bartlett's test is not significant
Cause: your correlation matrix is statistically indistinguishable from an identity matrix, which means the variables are effectively uncorrelated.
Fix: stop. There is nothing to reduce. Check first for a coding error or a variable entered as text, then accept the result. A non-significant Bartlett is itself a reportable finding.
The results say my file uploaded but the numbers look wrong
Cause: usually a header row read as data, a thousands separator, or a decimal comma in a European CSV.
Fix: check the preview table before you press Load. Numbers with commas as decimal separators must be converted first. Remove currency symbols and percentage signs, which turn a numeric column into text.
Retaining components by the Kaiser rule keeps far too many
Cause: the Kaiser rule is known to over-extract, and the problem grows with the number of variables. With 40 variables it often keeps 12 or more.
Fix: switch the retention dropdown to broken stick or to a cumulative variance target, and check the scree plot for the elbow. State which rule you used.
Rotation changed my percentages of variance
Cause: that is what rotation does. It redistributes variance between the retained components.
Fix: nothing is wrong. Check that the total across the retained set is unchanged, which it always is, and report the rotated percentages labelled as rotated. Communalities are also unchanged, which is the clearest proof nothing was invented.
The component scores do not match the ones from SPSS
Cause: SPSS defaults to regression-method factor scores, which are standardised to a variance of 1. This calculator, R and Python return scores whose variance equals the eigenvalue.
Fix: divide each column of scores by the square root of its eigenvalue to match the SPSS scaling. The correlations between scores and everything else are identical either way.
⚖ 16. Assumptions and Limitations
16.1 Assumptions
| # | Assumption | How to check it | Direction of bias if it fails |
|---|---|---|---|
| 1 | Linear relationships. PCA captures linear covariation only | Scatterplot matrix of every variable pair | Curved structure is split across several components, so the number retained is inflated and no component is interpretable. The arch effect in ecology is this failing |
| 2 | The variables are correlated. There must be shared variance to extract | Bartlett's test, KMO, and a scan of the correlation matrix for any |r| above 0.30 | With no correlation every eigenvalue sits near 1 and the components are pure noise |
| 3 | Adequate sample size. Enough cases to estimate the correlations stably | Cases per variable, absolute n, and the communalities together | Loadings are unstable and cumulative variance is overstated. A different sample gives a different solution |
| 4 | No perfect multicollinearity. No variable is an exact function of the others | Determinant of R above 0.00001, no correlation above 0.90 | The matrix is singular, an eigenvalue is exactly 0, and KMO cannot be computed |
| 5 | Interval or ratio measurement. Correlations must be meaningful | Inspect the measurement scale of each variable | Correlations between binary variables are bounded by their marginals, so loadings are artificially compressed and difficulty factors appear |
| 6 | No extreme outliers. A single case must not dominate | Boxplot each variable, then Mahalanobis distance across all of them | An outlier can define a whole component by itself, and the remaining components describe the rest of the data badly |
| 7 | Complete data. Every case has every variable | Count non-missing values per column | Pairwise deletion builds correlations from different case sets, which can make the matrix non positive definite and produce negative eigenvalues |
| 8 | One homogeneous population. No hidden groups | Colour the biplot by any grouping variable you have | PC1 becomes a group-separation axis and tells you nothing about within-group structure |
PCA does not assume multivariate normality. Normality matters only for Bartlett's test and for any inference about the components, not for the decomposition itself, which is pure linear algebra.
16.2 Limitations
- No significance test for the components. PCA is descriptive. For a formal test of dimensionality use parallel analysis, or confirmatory factor analysis if you have a hypothesis.
- Component names are interpretation, not measurement. Two competent researchers can name the same component differently. If the name matters, validate it against an external criterion.
- Sensitive to the variable set. Adding or removing one variable changes every loading. Solutions are not comparable across studies that measured different things.
- Linear only. Use kernel PCA, t-SNE or UMAP for curved structure, accepting that those axes are not interpretable.
- Not robust to outliers. Use robust principal component analysis when a few extreme cases are distorting the solution.
- Sign indeterminacy. Components are defined only up to a sign, so a convention must be stated whenever loadings are compared across studies.
- Cannot handle missing data natively. Use probabilistic PCA or multiple imputation when gaps are unavoidable.
- The retained components may not be the useful ones. PCA orders components by variance, not by relevance to your question. In principal component regression the component that predicts the outcome best is sometimes the fourth.
- Not a causal model. A component is a weighted sum of measured variables. It says nothing about what causes what.
- Scale-dependent when using covariance. Changing a variable from metres to centimetres changes the entire covariance solution, though it leaves the correlation solution untouched.
🏁 17. Conclusion
What principal component analysis is for
A PCA calculator answers one question: how few numbers can carry your data without losing what matters. It does that by rebuilding your variables as uncorrelated components ordered by the variance each one holds, then letting you keep the first few. In the worked example on this page, four exam subjects become two components holding 94.72% of the information, and both components have a name a teacher would recognise.
What it means in practice
The eigenvalue table is the finding, the loading table is the interpretation, and the scree plot is the evidence for how many components you kept. Everything else on this page supports one of those three. Once you have named your components you have a shorter dataset that a regression, a cluster analysis or a two-dimensional plot can actually work with.
Cautions
Three mistakes account for most bad PCA. Running it on the covariance matrix when the variables have different units, which lets one variable take over. Trusting the Kaiser rule without looking at the scree plot or the loadings. And naming a component from a loading of 0.35 because it was the only thing on the component. None of these produce an error message, which is why all three are so common.
Next steps
Run your own variables above, check KMO and Bartlett before anything else, choose your retention rule before you look at the eigenvalues, and turn on varimax rotation when a two-component solution is hard to name. Then export the component scores and use them. Principal component analysis is only finished when the components are doing work somewhere else in your analysis.
❓ 18. Frequently Asked Questions
What is a PCA calculator?
A PCA calculator is a tool that runs principal component analysis on your data. You enter several numeric variables and it returns the eigenvalues, the percentage of variance each component explains, the component loadings, the communalities and the component scores. This one also gives the KMO measure, Bartlett's test of sphericity, varimax rotation, a scree plot and a biplot, and it works entirely in your browser so no data leaves your computer.
How is PCA calculated, step by step?
There are six steps. Standardise each variable to a mean of 0 and a standard deviation of 1. Build the correlation matrix of the standardised variables. Find the eigenvalues and eigenvectors of that matrix. Sort the eigenvalues from largest to smallest, because that is the order of the components. Multiply each eigenvector by the square root of its eigenvalue to get the loadings. Finally, multiply the standardised data by the eigenvectors to get a score for every case on every component.
What is a good eigenvalue in PCA?
On a correlation matrix, an eigenvalue above 1.0 is the usual threshold, because 1.0 is the variance a single standardised variable already has. A component below 1.0 explains less than one original variable, so keeping it is a step backwards. This is the Kaiser criterion. It is a rule of thumb, not a law: check the scree plot and the loadings before you discard a component with an eigenvalue of 0.95.
How many principal components should I keep?
Use one rule, chosen before you look at the answer. The Kaiser criterion keeps components with an eigenvalue above 1. The scree test keeps components above the elbow of the curve. The cumulative variance rule keeps components until you reach 70% or 80%. The broken-stick model is the strictest. Parallel analysis is the most accurate in simulation studies. When the rules disagree, prefer the solution where every component has a name you can defend.
What is the difference between factor analysis and principal components?
PCA analyses all the variance in your variables and builds components from them. Factor analysis analyses only the shared variance and assumes hidden factors cause the variables. PCA puts 1.0 on the diagonal of the matrix; factor analysis puts estimated communalities there. PCA has no error term and gives a unique answer, while factor analysis has one and gives an infinite family of rotations. Use PCA to compress, factor analysis to model a construct.
What is a good loading value in PCA?
A loading is a correlation between a variable and a component, so it runs from minus 1 to plus 1. Above 0.70 in absolute size is excellent and defines the component. From 0.40 to 0.70 is worth interpreting. Between 0.32 and 0.40 is the usual minimum to report at all. Below 0.32 should be suppressed in the table. Apply one threshold across the whole table and state which one you used.
Should I use the correlation matrix or the covariance matrix?
Use the correlation matrix unless every variable is measured in the same unit on a comparable scale. The covariance matrix uses raw variances, so a variable measured in large numbers will dominate the first component regardless of whether it matters. The correlation matrix standardises everything first, which is why almost every published PCA uses it. This is the single setting that changes the answer most.
What is KMO and what value do I need?
The Kaiser-Meyer-Olkin measure of sampling adequacy compares ordinary correlations with partial correlations to check whether your variables share enough common variance for PCA. It runs from 0 to 1. Kaiser's labels are: below 0.50 unacceptable, 0.50 to 0.59 miserable, 0.60 to 0.69 mediocre, 0.70 to 0.79 middling, 0.80 to 0.89 meritorious, above 0.90 marvellous. The usual published floor is 0.60. With fewer than about six variables KMO is unstable and should be read as a hint.
What does Bartlett's test of sphericity tell me?
It tests whether your correlation matrix is an identity matrix, meaning every variable is uncorrelated with every other. A significant result, p below 0.05, says the correlations are strong enough that reducing them is worthwhile. It is a low bar: with a large sample it is almost always significant. A non-significant Bartlett is a genuine reason to stop, but a significant one is not evidence that your PCA will be good.
Does PCA give a p-value?
No. Principal component analysis is descriptive, not inferential. It re-describes your data in fewer dimensions and makes no claim about a population, so there is no p-value for a component, an eigenvalue or a loading. The only p-value on this page belongs to Bartlett's test, which checks whether the variables are correlated enough to bother reducing. For a formal test of how many components exist, use parallel analysis.
How much data do I need for PCA?
The traditional rules are 5 to 10 cases per variable, or an absolute minimum around 100. The modern position, from MacCallum and colleagues in 1999, is that it depends on your communalities: with communalities above 0.60 even 60 cases can work, with communalities near 0.50 you want 100 to 200, and with low communalities you may need 500. One hard limit applies always: you need more cases than variables, or the matrix is singular.
What is varimax rotation and does it change my results?
Varimax rotates the retained components as a rigid frame so each loading moves toward 0 or 1, making the components easier to name. It keeps the components uncorrelated. It does not change the total variance explained by the retained set, and it does not change any communality: it only redistributes variance between components. Rotate when you are naming components. Do not rotate when the components are feeding a regression, because there the ordering by variance is the point.
Why are my PCA loadings negative?
The sign of a component is mathematically arbitrary. An eigenvector multiplied by minus 1 is still a valid eigenvector with the same eigenvalue, so software applies its own convention or none at all. This calculator and scikit-learn make the largest loading in each component positive. R's prcomp applies no convention. A whole column flipping sign changes nothing about the interpretation, as long as you say which direction you called positive.
What is the difference between a loading and an eigenvector?
An eigenvector holds the weights used to build a component score from the standardised data. A loading is the correlation between an original variable and the component. On a correlation matrix, loading equals eigenvector element times the square root of the eigenvalue. Interpret loadings, not eigenvectors. This trips people up in R because prcomp calls its eigenvector matrix rotation, and in Python because sklearn calls it components_.
What is a communality in PCA?
A communality is the proportion of one variable's variance that is captured by the components you kept. It is the sum of that variable's squared loadings across the retained components, and it runs from 0 to 1. Above 0.60 means the solution represents that variable well. Below 0.40 means the variable is largely independent of the others and probably should not be in the analysis. One minus the communality is the uniqueness.
Can I do PCA in Excel?
Yes, but you have to build it yourself. Excel has no PCA function and the Analysis ToolPak has no PCA entry. Build the correlation matrix with CORREL or the ToolPak's Correlation tool, then find eigenvalues by power iteration using MMULT and SQRT(SUMSQ()), rescaling the vector each round until it stops moving. Deflate the matrix and repeat for each further component. Section 8 walks through all six steps with spreadsheet screenshots.
How do I run principal component analysis in R?
The one-liner is prcomp(dat, scale. = TRUE), where scale. = TRUE is essential because prcomp defaults to the covariance matrix. But prcomp returns standard deviations rather than eigenvalues, and its rotation element holds eigenvectors rather than loadings, so square the standard deviations for eigenvalues and multiply the rotation by them for loadings. Section 9 gives a complete base-R script that prints everything and saves a 300 dpi figure.
How do I run PCA in Python with sklearn?
Standardise first with StandardScaler, then fit sklearn.decomposition.PCA. Note that sklearn centres but does not scale, so feeding raw columns silently gives covariance PCA. Eigenvalues are in explained_variance_, percentages in explained_variance_ratio_, and eigenvectors in components_ as rows, so loadings are pca.components_.T times the square root of explained_variance_. Section 10 gives a full NumPy and SciPy script that also computes KMO and Bartlett, which sklearn does not provide.
What does a biplot show?
A biplot shows cases and variables on the same picture. Points are cases positioned by their scores on the first two components. Arrows are variables, drawn from the origin with a direction and length set by their loadings. Read it by angle: arrows pointing the same way are positively correlated variables, arrows at right angles are uncorrelated, and arrows pointing opposite ways are negatively correlated. A case sitting far along an arrow scored highly on that variable.
Can PCA be used on categorical or binary data?
Not directly. PCA is built on the correlation matrix, and correlations between binary variables are bounded by their marginal frequencies, which produces artificial difficulty factors rather than real structure. For categorical data use correspondence analysis, multiple correspondence analysis, or categorical PCA. Ordinal Likert items with five or more points are treated as continuous in practice and are widely published, but three-point scales are not safe.
📑 19. Cite This Tool
If this PCA calculator produced numbers that appear in your work, cite it alongside the statistical sources in Section 22.
StatsUnlock. (2026). PCA calculator: free online principal component analysis [Computer software]. https://statsunlock.com/pca-calculator/
@misc{statsunlock_pca_2026,
author = {{StatsUnlock}},
title = {{PCA Calculator: Free Online Principal Component Analysis}},
year = {2026},
howpublished = {\url{https://statsunlock.com/pca-calculator/}},
note = {Accessed: 2026}
}
Principal component analysis was performed on the correlation matrix of ___ variables measured on ___ cases using the StatsUnlock PCA Calculator (https://statsunlock.com/pca-calculator/). Sampling adequacy was assessed with the Kaiser-Meyer-Olkin measure (KMO = ___) and Bartlett's test of sphericity. Components were retained using ___, giving ___ component(s) that explained ___% of the total variance.
Run the analysis above and the Methods paragraph fills itself with your own values.
🔗 20. Related Tools
Tools on StatsUnlock that pair naturally with a principal component analysis.
📖 21. Glossary of Terms
| Term | Plain-English meaning |
|---|---|
| Bartlett's test of sphericity | A test of whether the correlation matrix is an identity matrix. A significant result means the variables are correlated enough for PCA to be worth running. |
| Biplot | A single picture showing cases as points and variables as arrows, both positioned by the first two components. |
| Broken-stick model | A retention rule that keeps a component only if its eigenvalue beats what you would expect if the total variance were divided at random. |
| Communality | The share of one variable's variance captured by the components you kept. Runs from 0 to 1. |
| Component score | The value one case takes on one component, built from that case's standardised data and the eigenvector weights. |
| Correlation matrix | A square table of the correlations between every pair of variables, with 1s on the diagonal. |
| Covariance matrix | The same table built from raw variances instead of correlations, so units matter. |
| Cross-loading | A variable that loads meaningfully on two or more components, so it cannot be assigned to either cleanly. |
| Cumulative variance | The running total of the percentage of variance explained by the components kept so far. |
| Determinant of R | A single number summarising the correlation matrix. Near 1 means no correlation, near 0 means severe multicollinearity. |
| Dimensionality reduction | Replacing many variables with fewer while keeping most of the information. |
| Eigenvalue | The amount of variance one component carries. On a correlation matrix the eigenvalues sum to the number of variables. |
| Eigenvector | The set of weights that builds one component from the standardised variables. Its length is fixed at 1. |
| Kaiser criterion | The rule that keeps components with an eigenvalue above 1.0. |
| KMO | Kaiser-Meyer-Olkin measure of sampling adequacy. Checks whether variables share enough common variance for PCA. |
| Loading | The correlation between an original variable and a component. What you interpret. |
| MSA | Measure of sampling adequacy for one variable, the per-variable version of KMO. |
| Orthogonal | At right angles, which for components means uncorrelated with each other. |
| Principal component | A new variable built as a weighted sum of the originals, chosen to carry as much remaining variance as possible. |
| Rotation | Turning the retained components so that loadings move toward 0 or 1, making them easier to name. Varimax keeps them uncorrelated. |
| Scree plot | A chart of eigenvalue against component number, used to find the elbow where the curve flattens. |
| Singular matrix | A correlation matrix that cannot be inverted, caused by an exact linear dependency between variables. |
| Standardise | To rescale a variable to a mean of 0 and a standard deviation of 1, so units cannot influence the analysis. |
| Uniqueness | One minus the communality. The share of a variable the retained components do not explain. |
| Z-score | A standardised value: how many standard deviations a raw value sits from its mean. |
📚 22. References
Twenty peer-reviewed journal articles behind every rule and threshold this principal component analysis calculator applies. Each has a resolvable DOI.
- Abdi, H., & Williams, L. J. (2010). Principal component analysis. WIREs Computational Statistics, 2(4), 433–459. https://doi.org/10.1002/wics.101
- Bartlett, M. S. (1950). Tests of significance in factor analysis. British Journal of Statistical Psychology, 3(2), 77–85. https://doi.org/10.1111/j.2044-8317.1950.tb00285.x
- Candès, E. J., Li, X., Ma, Y., & Wright, J. (2011). Robust principal component analysis? Journal of the ACM, 58(3), 1–37. https://doi.org/10.1145/1970392.1970395
- Cattell, R. B. (1966). The scree test for the number of factors. Multivariate Behavioral Research, 1(2), 245–276. https://doi.org/10.1207/s15327906mbr0102_10
- Fabrigar, L. R., Wegener, D. T., MacCallum, R. C., & Strahan, E. J. (1999). Evaluating the use of exploratory factor analysis in psychological research. Psychological Methods, 4(3), 272–299. https://doi.org/10.1037/1082-989X.4.3.272
- Gabriel, K. R. (1971). The biplot graphic display of matrices with application to principal component analysis. Biometrika, 58(3), 453–467. https://doi.org/10.1093/biomet/58.3.453
- Horn, J. L. (1965). A rationale and test for the number of factors in factor analysis. Psychometrika, 30(2), 179–185. https://doi.org/10.1007/BF02289447
- Hotelling, H. (1933). Analysis of a complex of statistical variables into principal components. Journal of Educational Psychology, 24(6), 417–441. https://doi.org/10.1037/h0071325
- Jackson, D. A. (1993). Stopping rules in principal components analysis: A comparison of heuristical and statistical approaches. Ecology, 74(8), 2204–2214. https://doi.org/10.2307/1939574
- Jolliffe, I. T., & Cadima, J. (2016). Principal component analysis: A review and recent developments. Philosophical Transactions of the Royal Society A, 374(2065), 20150202. https://doi.org/10.1098/rsta.2015.0202
- Kaiser, H. F. (1958). The varimax criterion for analytic rotation in factor analysis. Psychometrika, 23(3), 187–200. https://doi.org/10.1007/BF02289233
- Kaiser, H. F. (1960). The application of electronic computers to factor analysis. Educational and Psychological Measurement, 20(1), 141–151. https://doi.org/10.1177/001316446002000116
- Kaiser, H. F. (1974). An index of factorial simplicity. Psychometrika, 39(1), 31–36. https://doi.org/10.1007/BF02291575
- MacCallum, R. C., Widaman, K. F., Zhang, S., & Hong, S. (1999). Sample size in factor analysis. Psychological Methods, 4(1), 84–99. https://doi.org/10.1037/1082-989X.4.1.84
- Pearson, K. (1901). On lines and planes of closest fit to systems of points in space. The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science, 2(11), 559–572. https://doi.org/10.1080/14786440109462720
- Ringnér, M. (2008). What is principal component analysis? Nature Biotechnology, 26(3), 303–304. https://doi.org/10.1038/nbt0308-303
- Tipping, M. E., & Bishop, C. M. (1999). Probabilistic principal component analysis. Journal of the Royal Statistical Society: Series B, 61(3), 611–622. https://doi.org/10.1111/1467-9868.00196
- Velicer, W. F. (1976). Determining the number of components from the matrix of partial correlations. Psychometrika, 41(3), 321–327. https://doi.org/10.1007/BF02293557
- Zou, H., Hastie, T., & Tibshirani, R. (2006). Sparse principal component analysis. Journal of Computational and Graphical Statistics, 15(2), 265–286. https://doi.org/10.1198/106186006X113430
- Zwick, W. R., & Velicer, W. F. (1986). Comparison of five rules for determining the number of components to retain. Psychological Bulletin, 99(3), 432–442. https://doi.org/10.1037/0033-2909.99.3.432
