Python
Pandas
Data Analysis
Correlation Matrix
Data Visualization

Plot correlation matrix using pandas

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A correlation matrix is useful when you want a quick view of how numeric variables move together. In pandas, computing the matrix is easy with DataFrame.corr(). Plotting it usually means pairing pandas with a visualization library such as Matplotlib or seaborn. The important part is not just drawing the heatmap, but knowing which columns are being correlated and what kind of correlation you are asking for.

Compute the Correlation Matrix First

Start with the numeric data and call corr():

python
1import pandas as pd
2
3df = pd.DataFrame({
4    "height": [170, 165, 180, 175, 160],
5    "weight": [70, 60, 85, 78, 55],
6    "age": [30, 25, 40, 35, 22],
7})
8
9corr = df.corr()
10print(corr)

By default, pandas uses Pearson correlation, which measures linear association. This is often the expected starting point.

Plot with seaborn

The most common plotting approach is a heatmap:

python
1import matplotlib.pyplot as plt
2import seaborn as sns
3
4plt.figure(figsize=(6, 4))
5sns.heatmap(corr, annot=True, cmap="coolwarm", vmin=-1, vmax=1)
6plt.title("Correlation Matrix")
7plt.tight_layout()
8plt.show()

This is a strong default because:

  • color shows positive versus negative relationship
  • 'annot=True prints the actual coefficient values'
  • fixed vmin and vmax keeps the scale comparable across plots

If seaborn is available, this is usually the cleanest answer.

Plot with Matplotlib Only

If you want a lighter dependency stack, Matplotlib alone also works:

python
1import matplotlib.pyplot as plt
2
3fig, ax = plt.subplots(figsize=(6, 4))
4image = ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1)
5
6ax.set_xticks(range(len(corr.columns)))
7ax.set_yticks(range(len(corr.columns)))
8ax.set_xticklabels(corr.columns, rotation=45, ha="right")
9ax.set_yticklabels(corr.columns)
10
11fig.colorbar(image, ax=ax)
12plt.title("Correlation Matrix")
13plt.tight_layout()
14plt.show()

This gives you full control, though it requires a bit more manual labeling.

Pick the Right Correlation Method

Pandas supports different correlation methods:

python
pearson = df.corr(method="pearson")
spearman = df.corr(method="spearman")
kendall = df.corr(method="kendall")

Use them intentionally:

  • Pearson for linear relationships
  • Spearman for monotonic rank relationships
  • Kendall for ordinal-style association when robustness matters more than speed

Choosing the method is part of the analysis, not just a plotting option.

Use Only the Right Columns

Correlation is meaningful only for numeric variables. In mixed datasets, select the numeric columns explicitly:

python
numeric_df = df.select_dtypes(include="number")
corr = numeric_df.corr()

This avoids accidental issues with text columns and makes the plot easier to interpret.

It also helps when the DataFrame contains identifier columns such as IDs or ZIP-like codes that are technically numeric but not analytically meaningful. Those should often be excluded before computing correlations.

Improve Readability on Larger Matrices

For wide datasets, a plain heatmap becomes cluttered. A few practical improvements are:

  • increase figure size
  • rotate axis labels
  • round displayed values
  • show only one triangle of the symmetric matrix

Example using a mask:

python
1import numpy as np
2
3mask = np.triu(np.ones_like(corr, dtype=bool))
4
5plt.figure(figsize=(8, 6))
6sns.heatmap(corr, mask=mask, annot=True, cmap="coolwarm", vmin=-1, vmax=1)
7plt.tight_layout()
8plt.show()

This reduces visual duplication because the upper and lower triangles contain the same information.

Common Pitfalls

  • Plotting correlations for columns that are not numerically meaningful.
  • Interpreting correlation as causation.
  • Using Pearson correlation on data where only rank-based association makes sense.
  • Forgetting to standardize the color scale and then comparing plots unfairly.
  • Trying to annotate huge matrices where the labels become unreadable.

Summary

  • Use DataFrame.corr() to compute the matrix before plotting.
  • seaborn's heatmap is the most common and readable plotting approach.
  • Choose the correlation method intentionally instead of relying on defaults blindly.
  • Select numeric and meaningful columns before computing correlations.
  • For large matrices, mask one triangle and improve label formatting to keep the plot readable.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.