Bird
Raised Fist0
Matplotlibdata~20 mins

Correlation matrix visualization in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Correlation Matrix Visualization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of correlation matrix heatmap code
What will be the output of the following Python code that uses matplotlib and pandas to visualize a correlation matrix?
Matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [5, 4, 3, 2, 1],
    'C': [2, 3, 2, 3, 2]
})

corr = data.corr()
plt.imshow(corr, cmap='coolwarm', interpolation='none')
plt.colorbar()
plt.xticks(range(len(corr)), corr.columns)
plt.yticks(range(len(corr)), corr.columns)
plt.title('Correlation Matrix Heatmap')
plt.show()
AA line plot of the correlation values over the index with labels A, B, C on x-axis.
BA scatter plot of columns A vs B with a colorbar showing correlation values.
CA heatmap image showing correlation values with colors from blue (negative) to red (positive), labeled axes A, B, C, and a colorbar.
DA bar chart showing the correlation coefficients of each column with column A.
Attempts:
2 left
💡 Hint
Think about what plt.imshow does with a correlation matrix and the color map used.
❓ data_output
intermediate
1:30remaining
Number of cells in correlation matrix heatmap
Given a DataFrame with 4 columns, how many cells will the correlation matrix heatmap display?
Matplotlib
import pandas as pd
import numpy as np

data = pd.DataFrame(np.random.rand(10,4), columns=['W', 'X', 'Y', 'Z'])
corr = data.corr()
print(corr.shape)
A16
B8
C4
D10
Attempts:
2 left
💡 Hint
Correlation matrix is square with size equal to number of columns squared.
🔧 Debug
advanced
2:00remaining
Identify the error in correlation heatmap code
What error will this code raise when trying to plot a correlation matrix heatmap?
Matplotlib
import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})
corr = data.corr()
plt.imshow(corr, cmap='viridis')
plt.xticks(corr.columns)
plt.yticks(corr.columns)
plt.show()
AValueError: shape mismatch between ticks and data
BTypeError: 'Index' object cannot be interpreted as an integer
CSyntaxError: invalid syntax in plt.xticks line
DNo error, the plot will display correctly
Attempts:
2 left
💡 Hint
Check the arguments passed to plt.xticks and plt.yticks.
🚀 Application
advanced
2:30remaining
Best way to add correlation values on heatmap cells
Which code snippet correctly adds correlation coefficient numbers on each cell of a matplotlib heatmap of a correlation matrix?
Matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = pd.DataFrame(np.random.rand(5,3), columns=['A','B','C'])
corr = data.corr()
fig, ax = plt.subplots()
cax = ax.matshow(corr, cmap='coolwarm')
fig.colorbar(cax)
# Add correlation values here
plt.show()
A
for i in range(len(corr)):
    for j in range(len(corr)):
        ax.text(j, i, f'{corr.iloc[i,j]:.2f}', ha='center', va='center', color='white')
B
for i in range(len(corr)):
    for j in range(len(corr)):
        ax.text(i, j, f'{corr.iloc[i,j]:.2f}')
C
for i, j in corr:
    ax.text(i, j, f'{corr[i,j]:.2f}', ha='center', va='center')
D
for (i, j), val in np.ndenumerate(corr.values):
    ax.text(j, i, f'{val:.2f}', ha='center', va='center', color='black')
Attempts:
2 left
💡 Hint
Use np.ndenumerate to get row and column indices and values.
🧠 Conceptual
expert
1:30remaining
Interpretation of correlation matrix heatmap colors
In a correlation matrix heatmap using the 'coolwarm' colormap, what does a deep blue color in a cell represent?
AStrong negative correlation close to -1
BStrong positive correlation close to +1
CNo correlation close to 0
DMissing data or NaN value
Attempts:
2 left
💡 Hint
Recall the color scheme of 'coolwarm' where blue and red represent opposite ends.

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

  1. 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.
  2. Step 2: Connect visualization to understanding relationships

    Visualizing the matrix with colors helps quickly spot strong positive or negative correlations between variables.
  3. Final Answer:

    The strength and direction of relationships between variables -> Option B
  4. 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

  1. Step 1: Recall correct imshow parameters for correlation matrix

    Use cmap to set color map and interpolation='none' to avoid smoothing colors.
  2. 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.
  3. Final Answer:

    plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') -> Option A
  4. Quick Check:

    Correct imshow syntax = plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') [OK]
Hint: Use cmap and interpolation='none' with imshow for clear matrix [OK]
Common Mistakes:
  • Using invalid parameters like 'color' or 'style' in imshow
  • Forgetting interpolation='none' causing blurry colors
  • Trying to hide axes with 'axis' parameter inside imshow
3. Given the following code, what will be the output visualization?
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
data = np.random.rand(4,4)
corr_matrix = np.corrcoef(data)
plt.imshow(corr_matrix, cmap='viridis', interpolation='none')
plt.colorbar()
plt.show()
medium
A. A line plot showing correlation coefficients over time
B. A scatter plot of the original data points
C. A heatmap showing correlation values between 4 variables with colors from viridis colormap
D. An error because np.corrcoef cannot handle 2D arrays

Solution

  1. Step 1: Understand the code steps

    Data is a 4x4 random array, then np.corrcoef computes correlation matrix (4x4). imshow visualizes it with 'viridis' colors and a colorbar.
  2. Step 2: Identify the output type

    The output is a heatmap showing correlation strengths between variables, colored by viridis scale.
  3. Final Answer:

    A heatmap showing correlation values between 4 variables with colors from viridis colormap -> Option C
  4. Quick Check:

    Correlation matrix + imshow = heatmap [OK]
Hint: Correlation matrix + imshow + colorbar = heatmap visualization [OK]
Common Mistakes:
  • Confusing correlation matrix with scatter or line plots
  • Thinking np.corrcoef fails on 2D arrays
  • Ignoring the colorbar presence
4. You run this code but get a blurry correlation matrix image:
plt.imshow(corr_matrix, cmap='coolwarm')
plt.colorbar()
plt.show()
What is the likely cause and fix?
medium
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

  1. Step 1: Identify cause of blurry image

    By default, imshow applies interpolation which smooths colors, causing blur.
  2. Step 2: Fix by disabling interpolation

    Adding interpolation='none' disables smoothing, making each cell color sharp and clear.
  3. Final Answer:

    Missing interpolation='none' causes smoothing; add interpolation='none' to fix -> Option D
  4. 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?
hard
A. plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') plt.xticks(ticks=range(5), labels=var_names) plt.yticks(ticks=range(5), labels=var_names) plt.title('Correlation Matrix') plt.colorbar() plt.show()
B. plt.imshow(corr_matrix, cmap='coolwarm') plt.xlabel(var_names) plt.ylabel(var_names) plt.title('Correlation Matrix') plt.colorbar() plt.show()
C. plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') plt.axis('off') plt.title('Correlation Matrix') plt.colorbar() plt.show()
D. plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') plt.xticks(var_names) plt.yticks(var_names) plt.colorbar() plt.show()

Solution

  1. Step 1: Understand how to label axes in matplotlib heatmap

    Use plt.xticks and plt.yticks with ticks=range(n) and labels=var_names to set variable names on axes.
  2. Step 2: Check options for correct labeling and title

    plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') plt.xticks(ticks=range(5), labels=var_names) plt.yticks(ticks=range(5), labels=var_names) plt.title('Correlation Matrix') plt.colorbar() plt.show() correctly sets ticks and labels, adds title and colorbar. Others misuse xlabel, ylabel, or omit ticks.
  3. Final Answer:

    plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') plt.xticks(ticks=range(5), labels=var_names) plt.yticks(ticks=range(5), labels=var_names) plt.title('Correlation Matrix') plt.colorbar() plt.show() -> Option A
  4. Quick Check:

    Use xticks/yticks with ticks and labels [OK]
Hint: Use plt.xticks and plt.yticks with ticks and labels for axis names [OK]
Common Mistakes:
  • Using plt.xlabel/plt.ylabel for multiple tick labels
  • Forgetting to specify ticks in xticks/yticks
  • Turning axis off removes labels
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard