UK-based online statistics and data analysis support for USA, UK, and international clients. No exams, no impersonation, no fabricated data.
Correlation Tests

Correlation Matrix: Python, R, SPSS and Excel Complete Guide

Correlation, Pearson matrix, p-values, heatmaps and software workflow Correlation Matrix: Python, R, SPSS and Excel Complete Guide A Correlation Matrix is a square table that shows...

Statistics guide Ethical learning support SPSS/R/Python/Excel friendly
Correlation Matrix: Python, R, SPSS and Excel Complete Guide

Correlation, Pearson matrix, p-values, heatmaps and software workflow

Correlation Matrix: Python, R, SPSS and Excel Complete Guide

A Correlation Matrix is a square table that shows the correlation coefficient between every pair of numeric variables. This guide explains the Pearson correlation matrix with verified Python charts, R charts, SPSS output and an Excel worked file. You will learn how to interpret the heatmap, p-value matrix, strongest correlation pairs, G3 target correlations, pairwise sample sizes and final reporting wording.

AdvertisementGoogle AdSense top placement reserved here

Quick Answer: Correlation Matrix Result

The correlation matrix used 649 students and 16 numeric variables: age, Medu, Fedu, traveltime, studytime, failures, famrel, freetime, goout, Dalc, Walc, health, absences, G1, G2 and G3. The focused target variable was G3, the final grade.

The strongest correlation pair was G2 with G3, with r = 0.918548. This is a very strong positive relationship, meaning students with higher second-period grades usually also had higher final grades. The next strongest grade relationships were G1 with G2, r = 0.864982, and G1 with G3, r = 0.826387. The strongest negative relationship involving final grade was failures with G3, r = -0.393316.

Main methodPearson
Sample size649
Numeric variables16
Target variableG3

Top pairG2-G3
Top r0.9185
Top negative G3 pairfailures
Pairwise N649

Final interpretation: The matrix shows a strong grade-performance cluster. G1, G2 and G3 are strongly and positively related. Failures are negatively related to grade outcomes. The pairwise sample-size matrix confirms that each pair used 649 valid observations, so the matrix is stable and easy to compare across variables.

Table of Contents

  1. What Is a Correlation Matrix?
  2. Pearson Correlation Matrix Formula
  3. Dataset and Variables Used
  4. Verified Correlation Matrix Results
  5. Python Correlation Matrix Charts
  6. R Correlation Matrix Charts
  7. SPSS Correlation Matrix Output
  8. Excel Correlation Matrix Worked File
  9. Python, R, SPSS and Excel Workflows
  10. Code Blocks and Formulas
  11. How to Report a Correlation Matrix
  12. Common Mistakes
  13. Downloads and Resources
  14. Related Guides
  15. FAQs

What Is a Correlation Matrix?

A Correlation Matrix is a table that displays the correlation coefficient for every pair of numeric variables in a dataset. Each row and column contains the same variable names. The diagonal values are always 1 because every variable is perfectly correlated with itself.

The most common version is the Pearson correlation matrix. Pearson correlation measures linear association. A value near +1 means a strong positive linear relationship. A value near -1 means a strong negative linear relationship. A value near 0 means the linear relationship is weak.

A correlation matrix is useful when you want to quickly see which variables move together, which variables move in opposite directions and which variables are weakly related. It is also useful before multicollinearity checks, variance inflation factor review and regression modeling.

Simple definition: A correlation matrix is a compact table of pairwise correlations. It shows the direction and strength of association among all numeric variables at once.

Pearson Correlation Matrix Formula

Each cell in a Pearson correlation matrix is calculated using the Pearson correlation coefficient formula:

r = Σ[(x − x̄)(y − ȳ)] / √{Σ(x − x̄)2 × Σ(y − ȳ)2}

The formula compares how two variables vary together relative to how much each variable varies on its own. When the variables increase together, the coefficient is positive. When one variable increases while the other decreases, the coefficient is negative.

The p-value for each correlation tests the null hypothesis that the population correlation is zero. In this post, the p-value matrix is included so readers can see which correlations are statistically significant at the .05 level.

Dataset and Variables Used

The analysis used the student performance dataset. The focused target variable was G3, the final grade. The matrix included 16 numeric variables and all pairwise sample sizes were N = 649.

Variable GroupVariablesPurpose in Correlation Matrix
Grade variablesG1, G2, G3Measure how earlier grades relate to final grade performance.
Academic factorsstudytime, failures, absencesCheck study time, previous failures and absence patterns.
Family educationMedu, FeduCompare parental education variables with grades and with each other.
Student contextage, traveltime, famrel, freetime, goout, healthCheck background, lifestyle and wellbeing relationships.
Alcohol variablesDalc, WalcCheck weekday and weekend alcohol-use relationships.

The Excel worked file contains separate sheets for the dataset, numeric data, summary statistics, correlation matrix, pairwise N matrix, p-value matrix, strongest pairs and G3-focused correlations.

Verified Correlation Matrix Results

The strongest correlation pair in the matrix is G2 with G3, with r = 0.918548. This is a very strong positive relationship. The second strongest is G1 with G2, r = 0.864982, followed by G1 with G3, r = 0.826387.

RankVariable 1Variable 2Pairwise NPearson rDirectionStrengthDecision
1G2G36490.918548PositiveVery strongStatistically significant
2G1G26490.864982PositiveStrongStatistically significant
3G1G36490.826387PositiveStrongStatistically significant
4MeduFedu6490.647477PositiveModerateStatistically significant
5DalcWalc6490.616561PositiveModerateStatistically significant
6failuresG3649-0.393316NegativeWeak to moderateStatistically significant
7gooutWalc6490.388680PositiveWeak to moderateStatistically significant
8failuresG2649-0.385782NegativeWeak to moderateStatistically significant
9failuresG1649-0.384210NegativeWeak to moderateStatistically significant
10freetimegoout6490.346352PositiveWeak to moderateStatistically significant

For the focused target variable G3, the strongest positive correlations were G2, G1, studytime, Medu and Fedu. The strongest negative correlations with G3 were failures, Dalc, Walc, traveltime and freetime.

AdvertisementGoogle AdSense middle placement reserved here

Python Correlation Matrix Charts

The Python output includes six charts and a PDF report. These charts show the Pearson matrix, p-value matrix, strongest pairs, target-variable correlations, pairwise sample sizes and the strongest pair scatterplot.

Python Chart 1: Pearson Correlation Heatmap

Python Pearson correlation matrix heatmap for Correlation Matrix
Python Pearson correlation heatmap showing the complete matrix of numeric variables.

The Python Pearson heatmap shows the full linear correlation structure. The strongest positive block appears around G1, G2 and G3. The largest off-diagonal value is G2-G3, approximately 0.92. This means the second-period grade is very strongly related to the final grade.

The heatmap also shows negative relationships between failures and grade variables. These negative cells mean students with more previous failures tend to have lower grade scores.

Python Chart 2: Correlation p-value Heatmap

Python p-value heatmap for Correlation Matrix
Python p-value heatmap for testing Pearson correlations.

The p-value heatmap shows which Pearson correlations are statistically significant. Strong grade relationships have extremely small p-values. The chart is useful because a correlation matrix should not be interpreted only by color or coefficient size; significance testing adds evidence about whether the relationship is likely to be different from zero.

With 649 observations, even weak correlations may become statistically significant. The coefficient tells strength; the p-value tells statistical evidence.

Python Chart 3: Strongest Correlation Pairs

Python strongest correlation pairs chart
Python bar chart ranking the strongest Pearson correlation pairs.

This chart ranks correlations by absolute strength. The top three pairs are G2-G3, G1-G2 and G1-G3. These are all strong positive grade relationships. The chart also includes negative relationships such as failures-G3, making it easier to identify both strong positive and strong negative patterns.

Python Chart 4: Target Variable Correlations with G3

Python target variable correlations with G3
Python chart showing Pearson correlations with G3 final grade.

This chart focuses only on G3. The strongest positive bar is G2, followed by G1. Studytime and parental education variables are positive but much weaker. The strongest negative bar is failures, showing that prior failures are associated with lower final grades.

Python Chart 5: Pairwise Sample Size Matrix

Python pairwise sample size matrix for Correlation Matrix
Python matrix showing valid sample size for each pairwise correlation.

The pairwise sample size matrix confirms that each correlation used 649 valid observations. This is important because correlation matrices can become difficult to compare if some cells are based on fewer cases. Here, all displayed pairwise coefficients have the same N.

Python Chart 6: Top Correlation Scatterplot

Python top correlation scatterplot G2 and G3
Python scatterplot for the strongest correlation pair, G2 with G3.

The scatterplot confirms the strongest Pearson result visually. Points rise clearly from left to right, showing a strong positive relationship between G2 and G3. The fitted line supports the reported Pearson coefficient of about 0.9185.

R Correlation Matrix Charts

The R output validates the same correlation matrix with colorful charts. It includes a Pearson heatmap, p-value heatmap, strongest-pairs chart, target-variable chart, pairwise sample-size matrix and top-pair scatterplot.

R Chart 1: Pearson Correlation Heatmap

R Pearson correlation heatmap for Correlation Matrix
R Pearson correlation heatmap showing linear associations among numeric variables.

The R Pearson heatmap confirms the same main pattern as Python. The strongest cluster is formed by G1, G2 and G3. The G2-G3 value is the strongest relationship in the matrix.

R Chart 2: Correlation p-value Heatmap

R correlation p-value heatmap
R p-value heatmap for Pearson correlation tests.

The R p-value heatmap highlights which relationships are statistically significant. The grade relationships and several academic-background relationships show very small p-values. This supports the conclusion that the main observed patterns are not random noise.

R Chart 3: Strongest Correlation Pairs

R strongest correlation pairs chart
R bar chart ranking strongest Pearson correlation pairs.

The R strongest-pairs chart makes the ranking easy to interpret. G2-G3 is first, followed by G1-G2 and G1-G3. Negative grade relationships with failures are also shown clearly.

R Chart 4: Target Variable Correlations

R target variable correlations with G3
R chart showing correlations with G3 final grade.

The R target-variable chart shows that G2 and G1 dominate positive correlations with G3. Failures are the strongest negative correlate. This chart is helpful for readers who care mainly about final grade rather than the entire matrix.

R Chart 5: Pairwise Sample Size Matrix

R pairwise sample size matrix
R sample size matrix showing N for each pairwise correlation.

The R pairwise sample-size heatmap confirms that the same number of valid observations was used across the displayed matrix. This strengthens the comparison between coefficients because the reader is not comparing one pair based on many cases with another pair based on fewer cases.

R Chart 6: Top Correlation Scatterplot

R top correlation scatterplot G2 and G3
R scatterplot for the strongest Pearson pair, G2 with G3.

The R scatterplot validates the same strong positive relationship. The upward pattern between G2 and G3 is clear, which supports the very high Pearson coefficient. This chart is the easiest visual proof that the strongest matrix value is meaningful.

SPSS Correlation Matrix Output

The SPSS output provides a formal correlation matrix report suitable for students, assignments and thesis-style documentation. It shows Pearson correlations, significance values and valid sample sizes in the SPSS Viewer format.

Open the SPSS Correlation Matrix Output PDF

SPSS Output ElementWhat It ShowsHow to Interpret It
Pearson CorrelationThe coefficient r for every variable pair.Positive values mean variables increase together; negative values mean opposite direction.
Sig. 2-tailedThe p-value for the correlation test.If p < .05, the relationship is statistically significant.
NValid paired sample size.Shows how many observations were used for each correlation.
Diagonal valuesEach variable correlated with itself.Always 1.000 and not interpreted as a substantive result.

The SPSS output should be used when a formal PDF report is needed. The interpretation remains the same as Python, R and Excel: the strongest relationship is between G2 and G3, while failures are negatively related to grades.

Excel Correlation Matrix Worked File

The Excel worked file contains the dataset, numeric data, summary statistics, correlation matrix, pairwise N matrix, p-value matrix, strongest pairs and G3-focused correlations. It is useful for students who want to see the formulas behind the matrix rather than only the finished chart.

Download the Excel Correlation Matrix Worked File

Excel SheetPurposeWhy It Matters
READMEExplains the workbook method and notes.Helps readers understand the file structure before using formulas.
DatasetOriginal data.Shows the variables before analysis.
Numeric_DataNumeric columns only.Correlation matrix requires numeric variables.
Summary_StatsN, missing, mean, standard deviation and quartiles.Checks data quality before correlation.
Correlation_MatrixPearson r values.Main matrix used for interpretation.
Pairwise_NValid sample size for each pair.Confirms all pairs use sufficient data.
P_ValuesTwo-tailed p-values.Shows statistical significance of each relationship.
Strongest_PairsRanked correlation pairs.Identifies the most important relationships quickly.
G3_CorrelationsTarget-variable view.Focuses directly on final grade G3.

The Excel file uses the standard Pearson correlation idea and calculates p-values using the t-test transformation:

t = r × √[(n − 2) / (1 − r²)]

The two-tailed p-value is then calculated from the t distribution. This makes the workbook a useful teaching file because it shows both the coefficient and its significance test.

AdvertisementGoogle AdSense in-content placement reserved here

Python, R, SPSS and Excel Workflows for Correlation Matrix

SoftwareMain StepsBest Use
PythonUse pandas to select numeric variables, scipy for p-values and matplotlib for heatmaps/scatterplots.Automated reporting, chart generation and reproducible analysis.
RUse cor(), cor.test(), p.adjust(), matrix reshaping and R charts.Statistical validation and publication-style graphics.
SPSSUse Analyze → Correlate → Bivariate or CORRELATIONS syntax.Formal output tables and PDF reporting.
ExcelUse CORREL, COUNT, T.DIST.2T, formulas and conditional formatting.Formula-based teaching and easy spreadsheet review.

Code Blocks and Formulas

Python Code for Correlation Matrix

import pandas as pd
import numpy as np
from scipy import stats

df = pd.read_csv("dataset.csv")
numeric_df = df.select_dtypes(include=[np.number])

corr_matrix = numeric_df.corr(method="pearson")

cols = numeric_df.columns
pvals = pd.DataFrame(np.nan, index=cols, columns=cols)
pairwise_n = pd.DataFrame(np.nan, index=cols, columns=cols)

for x in cols:
    for y in cols:
        pair = numeric_df[[x, y]].dropna()
        pairwise_n.loc[x, y] = len(pair)
        if x != y and len(pair) >= 3:
            r, p = stats.pearsonr(pair[x], pair[y])
            pvals.loc[x, y] = p

corr_matrix.to_csv("correlation_matrix.csv")
pvals.to_csv("correlation_p_values.csv")
pairwise_n.to_csv("pairwise_sample_sizes.csv")

print(corr_matrix.round(3))

R Code for Correlation Matrix

df <- read.csv("dataset.csv", stringsAsFactors = FALSE)
numeric_df <- df[sapply(df, is.numeric)]

corr_matrix <- cor(numeric_df, use = "pairwise.complete.obs", method = "pearson")

vars <- names(numeric_df)
p_matrix <- matrix(NA, nrow = length(vars), ncol = length(vars),
                   dimnames = list(vars, vars))
n_matrix <- matrix(NA, nrow = length(vars), ncol = length(vars),
                   dimnames = list(vars, vars))

for(i in vars){
  for(j in vars){
    pair_data <- numeric_df[, c(i, j)]
    pair_data <- pair_data[complete.cases(pair_data), ]
    n_matrix[i, j] <- nrow(pair_data)

    if(i != j && nrow(pair_data) >= 3){
      test <- cor.test(pair_data[[i]], pair_data[[j]], method = "pearson")
      p_matrix[i, j] <- test$p.value
    }
  }
}

write.csv(round(corr_matrix, 6), "correlation_matrix_r.csv")
write.csv(p_matrix, "correlation_p_values_r.csv")
write.csv(n_matrix, "pairwise_sample_sizes_r.csv")

print(round(corr_matrix, 3))

SPSS Syntax for Correlation Matrix

* Correlation Matrix in SPSS.
OUTPUT CLOSE ALL.
OUTPUT NEW NAME=Correlation_Matrix_Output.

CORRELATIONS
  /VARIABLES=age Medu Fedu traveltime studytime failures famrel freetime goout Dalc Walc health absences G1 G2 G3
  /PRINT=TWOTAIL NOSIG
  /MISSING=PAIRWISE.

OUTPUT EXPORT
  /CONTENTS EXPORT=VISIBLE
  /PDF DOCUMENTFILE='Correlation-Matrix-SPSS-Output.pdf'.

Excel Formulas for Correlation Matrix

Correlation coefficient:
=CORREL(variable_x_range, variable_y_range)

Pairwise sample size:
=COUNT(variable_x_range)

t statistic for correlation:
=r*SQRT((n-2)/(1-r^2))

Two-tailed p-value:
=T.DIST.2T(ABS(t), n-2)

Decision:
=IF(p_value<0.05,"Statistically significant","Not statistically significant")

How to Report a Correlation Matrix

A correlation matrix report should describe the method, sample size, strongest positive relationships, strongest negative relationships, target-variable findings and whether p-values were tested. Do not report every cell in a large matrix. Summarize the most important patterns.

APA-style report: A Pearson correlation matrix was calculated for 16 numeric variables using 649 students. The strongest positive relationship was between G2 and G3, r = .919, indicating a very strong association between second-period grade and final grade. G1 was also strongly associated with G2, r = .865, and G3, r = .826. The strongest negative relationship involving final grade was between failures and G3, r = -.393. These results show that previous grade performance is strongly related to final grade, while previous failures are associated with lower final grade outcomes.

Important reporting note: A correlation matrix shows association, not causation. The strong relationship between G2 and G3 does not prove that G2 causes G3. It means the two grade variables move together strongly in this dataset.

Common Mistakes in Correlation Matrix Interpretation

MistakeWhy It Is a ProblemBetter Practice
Reporting every cellLarge matrices become unreadable.Summarize strongest pairs and target-variable findings.
Ignoring p-valuesA coefficient alone does not show statistical evidence.Include a p-value matrix or significance note.
Ignoring sample sizeDifferent pairs may use different valid observations.Check the pairwise sample size matrix.
Confusing correlation with causationCorrelation does not prove cause and effect.Use wording like “associated with” or “related to.”
Using non-numeric variables directlyPearson correlation requires numeric data.Select numeric variables or code categories properly.
Ignoring multicollinearityStrong predictor-predictor correlations can affect regression.Check VIF before regression modeling.

Downloads and Resources

FAQs About Correlation Matrix

What is a correlation matrix?

A correlation matrix is a table that shows the correlation coefficient between every pair of numeric variables. It helps identify strong positive, strong negative and weak relationships.

What is the strongest correlation in this report?

The strongest correlation is between G2 and G3, with r = 0.918548. This is a very strong positive relationship.

How do I interpret negative values in a correlation matrix?

A negative value means one variable tends to decrease as the other increases. In this report, failures are negatively related to G3 final grade.

Can Excel create a correlation matrix?

Yes. Excel can create a correlation matrix using the CORREL function, Data Analysis ToolPak or formulas. The worked file in this guide includes formulas for r, p-values and decisions.

What is the difference between a correlation matrix and p-value matrix?

The correlation matrix shows the size and direction of relationships. The p-value matrix shows whether each relationship is statistically significant.

Does a correlation matrix prove causation?

No. A correlation matrix shows association only. It does not prove cause and effect.

AdvertisementGoogle AdSense bottom placement reserved here

Need help applying this to your own data?

Salar Cafe can help interpret output, clean datasets, review assumptions, build dashboards and explain statistical results ethically.

Need help interpreting your data analysis results?

Contact Salar Cafe
Engr. Muhammad Yar Saqib author profile photo

Engr. Muhammad Yar Saqib

WhatsApp Get Data Analysis Help