Python / Data Science Essentials Interview Questions
How do you create and interpret a correlation heatmap with Seaborn?
A correlation heatmap is one of the first plots every data scientist makes on a new dataset. It shows the Pearson (or other) correlation coefficient between every pair of numeric features as a colour-coded grid, immediately revealing which variables move together and which do not.
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Load example dataset df = sns.load_dataset('penguins').select_dtypes('number') # Compute correlation matrix corr = df.corr() # Pearson by default; method='spearman' for ranked print(corr) # --- Basic heatmap --- fig, ax = plt.subplots(figsize=(7, 5)) sns.heatmap( corr, annot=True, # show values inside each cell fmt='.2f', # 2 decimal places cmap='coolwarm', # blue = negative, red = positive vmin=-1, vmax=1, # fix colour scale to [-1, 1] linewidths=0.5, # add grid lines between cells ax=ax, ) ax.set_title('Feature Correlation Matrix') fig.tight_layout() # --- Mask upper triangle (remove redundancy) --- import numpy as np mask = np.triu(np.ones_like(corr, dtype=bool)) sns.heatmap(corr, mask=mask, annot=True, fmt='.2f', cmap='coolwarm', vmin=-1, vmax=1)
Interpreting the output: values close to +1 mean strong positive linear correlation (both variables increase together), values close to -1 mean strong negative correlation (one increases as the other decreases), and values near 0 indicate little to no linear relationship. The diagonal is always 1.0 (a variable is perfectly correlated with itself). Masking the upper triangle removes the mirror image and makes the chart less cluttered.
More Related questions...