0
0
Matplotlibdata~20 mins

Correlation matrix visualization in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style9 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.