DS Visualization with seaborn
seaborn is a statistical plotting library built on Matplotlib. It works directly with DataFrames: you name the columns for x, y, colour (hue) and so on, and it handles grouping, legends and statistical summaries such as regression lines and confidence bands.
import seaborn as snsEvery seaborn function draws onto a Matplotlib axes, so everything you know about plt.xlabel, plt.title and plt.show() still applies.
Note: The first run that imports seaborn takes a few seconds longer: the playground installs it on demand.
Choosing the right chart
| Question | Chart | seaborn |
|---|---|---|
| How is one variable distributed? | histogram / density | histplot, kdeplot |
| How do groups compare? | box / violin / bar | boxplot, violinplot, barplot |
| How do two numbers relate? | scatter (+ fit line) | scatterplot, regplot |
| How does something change over time? | line | lineplot |
| How do many variables relate? | heatmap / pair grid | heatmap, pairplot |
Distributions by group
histplot with hue overlays one histogram per group; kde=True adds a smoothed density curve:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
bikes["day_type"] = np.where(bikes["weekend"] == 1, "weekend", "weekday")
fig, ax = plt.subplots(figsize=(7, 4))
sns.histplot(data=bikes, x="rides", hue="day_type", bins=12, kde=True, ax=ax)
ax.set_title("Daily rides by day type")
plt.show()
print(bikes.groupby("day_type")["rides"].median())day_type
weekday 319.0
weekend 445.5
Name: rides, dtype: float64
Relationships with a fitted line
regplot draws a scatter plot plus the least-squares line and a shaded 95 % confidence band — the visual counterpart of the regression lessons:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
sns.regplot(data=bikes, x="temp_c", y="rides", ax=axes[0], scatter_kws={"s": 15})
sns.regplot(data=bikes, x="humidity", y="rides", ax=axes[1], scatter_kws={"s": 15},
color="grey")
axes[0].set_title("Strong relationship")
axes[1].set_title("No relationship")
plt.tight_layout()
plt.show()
print("Left: temperature, right: humidity")Left: temperature, right: humidity
The confidence band around the humidity line is wide enough to contain a flat line — the picture of a large p-value.
Comparing groups and adding a third variable
scatterplot can map extra columns to colour (hue), marker style (style) and size (size). Here rain becomes the point size and day type the colour, so one chart shows four variables:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
bikes["day_type"] = np.where(bikes["weekend"] == 1, "weekend", "weekday")
fig, axes = plt.subplots(1, 2, figsize=(12, 4), gridspec_kw={"width_ratios": [2, 1]})
sns.scatterplot(data=bikes, x="temp_c", y="rides", hue="day_type", size="rain_mm",
sizes=(20, 200), ax=axes[0])
axes[0].set_title("Rides vs temperature (size = rain)")
axes[0].legend(loc="upper left", fontsize=8)
sns.boxplot(data=bikes, x="day_type", y="rides", ax=axes[1])
axes[1].set_title("Rides by day type")
plt.tight_layout()
plt.show()
print("Scatter with", bikes["day_type"].nunique(), "colours and a box plot")Scatter with 2 colours and a box plot
In the scatter, the large (rainy) points sit below their neighbours — rain pulls rides down at every temperature.
A correlation heatmap in one call
The heatmap from the Correlation Matrix lesson took a dozen lines of Matplotlib. seaborn needs one:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
corr = bikes.drop(columns="date").corr()
fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(corr, annot=True, fmt=".2f", cmap="RdBu_r", vmin=-1, vmax=1, square=True, ax=ax)
ax.set_title("Correlation matrix")
plt.tight_layout()
plt.show()
print("Strongest predictor of rides:", corr["rides"].drop("rides").abs().idxmax())Strongest predictor of rides: temp_c
Good chart habits
- One message per chart. Put the message in the title: "Weekends are busier", not "Rides by day type".
- Label axes with units.
temp (°C),rides per day. - Start bar charts at zero; scatter and line charts may zoom in.
- Use colour with purpose — to separate groups or encode a value, not for decoration — and prefer colour-blind-safe palettes (seaborn's defaults are).
- Show the data, not just a summary: a box plot or scatter beats a single bar of means when the sample is small.
Test yourself
Which seaborn function draws a scatter plot with a least-squares line and confidence band?
sns.lineplotsns.regplotsns.histplotsns.heatmap
What does the hue argument do?
- Sets the figure size
- Colours the marks by the values of another column
- Changes the chart type
- Adds a title
Which chart best shows how daily rides are distributed for weekdays vs weekends?
- Pie chart
- Box plot or overlaid histograms
- Line chart over time
- Heatmap