A correlation matrix visualization helps you see how different things relate to each other. It shows which pairs move together or in opposite ways.
0
0
Correlation matrix visualization in Matplotlib
Introduction
To understand relationships between different features in a dataset before building a model.
To find which variables are strongly connected in a business report.
To check if some data columns are very similar or redundant.
To explore patterns in survey or experimental data.
To communicate data insights visually to others.
Syntax
Matplotlib
import matplotlib.pyplot as plt import seaborn as sns corr_matrix = data.corr() sns.heatmap(corr_matrix, annot=True, cmap='coolwarm') plt.show()
data.corr() calculates the correlation matrix from your data.
sns.heatmap() draws the colored grid showing correlation values.
Examples
Shows correlation with numbers inside squares and a 'viridis' color style.
Matplotlib
import seaborn as sns import matplotlib.pyplot as plt corr = df.corr() sns.heatmap(corr, annot=True, cmap='viridis') plt.show()
Colors blue to red with white at zero, highlighting positive and negative correlations.
Matplotlib
sns.heatmap(df.corr(), cmap='bwr', center=0) plt.show()
Shows correlation values rounded to 2 decimals with lines between cells.
Matplotlib
sns.heatmap(df.corr(), annot=True, fmt='.2f', linewidths=0.5) plt.show()
Sample Program
This code creates a small dataset with age, income, and score. It calculates how these relate and shows a colored grid with numbers.
Matplotlib
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Create sample data data = pd.DataFrame({ 'age': [25, 32, 47, 51, 62], 'income': [50000, 60000, 80000, 90000, 120000], 'score': [200, 220, 250, 270, 300] }) # Calculate correlation matrix corr_matrix = data.corr() # Plot heatmap sns.heatmap(corr_matrix, annot=True, cmap='coolwarm') plt.title('Correlation Matrix') plt.show()
OutputSuccess
Important Notes
Correlation values range from -1 (perfect opposite) to 1 (perfect match).
Colors help spot strong or weak relationships quickly.
Always check data types before calculating correlation; non-numeric columns are ignored.
Summary
A correlation matrix shows how pairs of variables move together.
Heatmaps color-code these relationships for easy understanding.
Use data.corr() and seaborn.heatmap() to create this visualization.