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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
