Seaborn — Statistical Visualization
sns.histplot(), compare groups with sns.boxplot(), color points by category with sns.scatterplot()'s hue, visualize a correlation matrix with sns.heatmap(), and get every pairwise relationship at once with sns.pairplot().
Why Seaborn?
Matplotlib gives you total control, but that control comes at a cost — every color, gridline, and axis label is something you set by hand. Seaborn wraps Matplotlib with sensible statistical defaults and a data= argument that takes a DataFrame directly, so most calls look like sns.something(data=df, x="col_a", y="col_b") instead of manually slicing out NumPy arrays first.
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd sns.set_theme(style="darkgrid") # applies Seaborn's styling to every chart from here on df = pd.DataFrame({ "product": ["Laptop", "Mouse", "Monitor", "Keyboard", "Laptop", "Mouse", "Monitor", "Keyboard"], "price": [1200, 45, 890, 65, 1150, 40, 910, 70], "rating": [4.5, 4.0, 4.2, 3.8, 4.6, 4.1, 4.3, 3.9], "region": ["West", "West", "East", "South", "East", "North", "West", "East"], })
Axes object (or a whole grid, for figure-level functions like pairplot), so plt.show(), ax.set_title(), and everything else from the Matplotlib lesson still works exactly the same way here.sns.histplot() — Distributions
sns.histplot() is Seaborn's version of a histogram, with an optional smoothed density curve (a KDE — kernel density estimate) layered on top to make the overall shape of the distribution easier to see.
sns.histplot(data=df, x="price", bins=6, kde=True, color="#4f9eff") plt.title("Distribution of Product Prices") plt.show()
sns.boxplot() — Comparing Groups
A box plot summarizes a numeric column's spread — median, quartiles, and outliers — for each category in another column, all side by side. It's the fast way to compare distributions across groups instead of just their averages.
sns.boxplot(data=df, x="region", y="price", hue="region", legend=False) plt.title("Price Spread by Region") plt.show()
sns.scatterplot() with hue
sns.scatterplot() works like Matplotlib's scatter, but the hue parameter automatically colors each point by a categorical column and adds a matching legend — no manual color-mapping loop required.
sns.scatterplot(data=df, x="price", y="rating", hue="region", s=100) plt.title("Price vs. Rating, by Region") plt.show()
hue isn't unique to scatterplot — sns.histplot(data=df, x="price", hue="region") overlays a separate distribution per region, and sns.boxplot(..., hue="region") further splits each x-axis category by region. It's one of the most-used arguments in the whole library.sns.heatmap() — Correlation Matrices
A correlation matrix, produced by pandas' .corr(), is itself just a grid of numbers between -1 and 1 — hard to scan as a table once you have more than a few columns. sns.heatmap() colors that grid, so strong positive or negative relationships jump out visually.
numeric_df = df[["price", "rating"]] corr = numeric_df.corr() print(corr) # price rating # price 1.000000 0.968... # rating 0.968... 1.000000 sns.heatmap(corr, annot=True, cmap="coolwarm", vmin=-1, vmax=1) plt.title("Correlation Matrix") plt.show()
.corr() silently ignores non-numeric columns like product or region — it's why numeric_df is sliced down to just price and rating first. Passing a mixed-type DataFrame straight into .corr() without selecting numeric columns can raise an error or drop columns unexpectedly depending on the pandas version, so it's best to select the numeric columns explicitly before calling it.annot=True prints each correlation value directly on its cell. cmap="coolwarm" picks a diverging color scale — blue for negative, red for positive. vmin=-1, vmax=1 pins the color scale to correlation's actual range, so a heatmap of a mostly-weak-correlation dataset isn't misleadingly stretched to look strong.sns.pairplot() — Every Relationship at Once
sns.pairplot() builds a grid of scatter plots for every pair of numeric columns in a DataFrame, with a histogram (or KDE) on the diagonal for each column against itself — a fast way to eyeball every relationship in a dataset in one call, without writing a chart for each pair by hand.
sns.pairplot(df, hue="region", vars=["price", "rating"]) plt.show()
pairplot() is a "figure-level" function — it returns a PairGrid object managing multiple subplots at once, unlike the "axes-level" functions earlier in this lesson (histplot, boxplot, scatterplot, heatmap), which each draw into a single Axes and can be placed inside a Matplotlib subplot grid alongside other charts.Lesson Summary
Let's recap everything you learned in this lesson:
data=.kde=True curve..corr().kde=True?sns.heatmap() most commonly visualize?sns.pairplot(df, vars=["price", "rating"]) produce?Build a small statistical report on the df from Section 1.
Using the
df from Section 1 (product, price, rating, region), write code that: (1) draws a sns.boxplot() of price grouped by region, (2) draws a sns.scatterplot() of price vs. rating with hue="region", and (3) computes df[["price", "rating"]].corr() and visualizes it with sns.heatmap(annot=True).
Rules: Call
plt.show() after each chart, and give each one a plt.title() describing what it shows.
💡 Show hints if you're stuck
- Step 1:
sns.boxplot(data=df, x="region", y="price") - Step 2:
sns.scatterplot(data=df, x="price", y="rating", hue="region") - Step 3:
sns.heatmap(df[["price", "rating"]].corr(), annot=True, cmap="coolwarm")