📖 Scenario: You work as a data analyst and want to understand how different features in a dataset relate to each other. Visualizing the correlation matrix helps you see which features move together.
🎯 Goal: Create a correlation matrix from a dataset and visualize it using a heatmap with matplotlib.
📋 What You'll Learn
Create a pandas DataFrame with given data
Calculate the correlation matrix using pandas
Visualize the correlation matrix as a heatmap using matplotlib
Label the heatmap axes with feature names
💡 Why This Matters
🌍 Real World
Correlation matrices help analysts understand relationships between variables in datasets, which is useful in fields like finance, healthcare, and marketing.
💼 Career
Data scientists and analysts often visualize correlations to select features for models or to explain data insights to stakeholders.
Progress0 / 4 steps
1
Create the dataset
Create a pandas DataFrame called df with these exact columns and values: 'Height': [150, 160, 170, 180, 190], 'Weight': [50, 60, 65, 80, 90], 'Age': [25, 30, 35, 40, 45]
Matplotlib
Hint
Use pd.DataFrame with a dictionary where keys are column names and values are lists of numbers.
2
Calculate the correlation matrix
Create a variable called corr_matrix that stores the correlation matrix of df using the corr() method.
Matplotlib
Hint
Use df.corr() to get the correlation matrix.
3
Visualize the correlation matrix
Import matplotlib.pyplot as plt. Use plt.imshow() to display corr_matrix as a heatmap with the cmap set to 'coolwarm'. Add a color bar with plt.colorbar().
Matplotlib
Hint
Use plt.imshow() with cmap='coolwarm' and add a color bar with plt.colorbar().
4
Add labels and show the plot
Set the x-axis and y-axis ticks to the column names of df using plt.xticks() and plt.yticks(). Rotate the x-axis labels by 45 degrees. Finally, call plt.show() to display the heatmap.
Matplotlib
Hint
Use plt.xticks() and plt.yticks() with ticks=range(len(df.columns)) and labels=df.columns. Rotate x labels by 45 degrees. Then call plt.show().
Practice
(1/5)
1. What does a correlation matrix visualization primarily help you understand in data science?
easy
A. The total number of missing values in the data
B. The strength and direction of relationships between variables
C. The order of rows in a dataset
D. The exact values of each data point in the dataset
Solution
Step 1: Understand the purpose of a correlation matrix
A correlation matrix shows how variables relate to each other, indicating strength and direction of relationships.
Step 2: Connect visualization to understanding relationships
Visualizing the matrix with colors helps quickly spot strong positive or negative correlations between variables.
Final Answer:
The strength and direction of relationships between variables -> Option B
Quick Check:
Correlation matrix = relationships [OK]
Hint: Correlation matrix shows variable relationships, not raw data [OK]
Common Mistakes:
Confusing correlation matrix with raw data values
Thinking it shows missing data counts
Assuming it orders dataset rows
2. Which of the following is the correct way to display a correlation matrix using matplotlib's imshow function?
easy
A. plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none')
B. plt.imshow(corr_matrix, color='red')
C. plt.imshow(corr_matrix, style='heatmap')
D. plt.imshow(corr_matrix, axis='off')
Solution
Step 1: Recall correct imshow parameters for correlation matrix
Use cmap to set color map and interpolation='none' to avoid smoothing colors.
Step 2: Evaluate options
plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') correctly uses cmap='coolwarm' and interpolation='none'. Others use invalid or unsupported parameters.
Final Answer:
plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') -> Option A
A. The colormap 'coolwarm' is invalid; use 'viridis' instead
B. The correlation matrix must be normalized before plotting
C. You forgot to call plt.show(), so image is blurry
D. Missing interpolation='none' causes smoothing; add interpolation='none' to fix
Solution
Step 1: Identify cause of blurry image
By default, imshow applies interpolation which smooths colors, causing blur.
Step 2: Fix by disabling interpolation
Adding interpolation='none' disables smoothing, making each cell color sharp and clear.
Final Answer:
Missing interpolation='none' causes smoothing; add interpolation='none' to fix -> Option D
Quick Check:
Interpolation='none' stops blur [OK]
Hint: Add interpolation='none' to imshow to avoid blurry colors [OK]
Common Mistakes:
Changing colormap instead of fixing interpolation
Forgetting plt.show() does not affect blur
Normalizing matrix is unnecessary for visualization
5. You have a dataset with 5 variables and want to visualize their correlation matrix with variable names on axes. Which code snippet correctly adds labels and a title to the heatmap?