Advanced·15 min·datascience · matplotlib · seaborn · viz
Plotting with matplotlib & seaborn
Two libraries cover 95% of what you'll ever need:
- matplotlib — the foundation. Explicit, controllable.
- seaborn — sits on top of matplotlib, defaults are prettier, statistical charts one-liner.
matplotlib mental model
fig, ax = plt.subplots() # figure = canvas, ax = one plot
ax.plot(x, y)
ax.set_title(...); ax.set_xlabel(...); ax.set_ylabel(...)
plt.tight_layout(); plt.savefig("out.png")
plt.subplots(2, 3)— grid of plots;axesis a 2D array.- Everything is customizable — colors, linewidth, markers, ticks, log scale.
When to use each chart
- Line — series over time, trends.
- Bar — categorical comparisons.
- Histogram — distribution of one variable.
- KDE (
sns.kdeplot) — smoothed histogram. - Boxplot / Violin — distribution across groups.
- Scatter — two variables, correlation.
- Heatmap — 2D matrix, e.g. correlation matrix.
seaborn one-liners
import seaborn as sns
sns.set_theme(style="whitegrid")
sns.barplot(data=df, x="region", y="revenue", hue="product")
sns.lineplot(data=df, x="date", y="sales", hue="channel")
sns.heatmap(df.corr(numeric_only=True), annot=True, cmap="RdBu_r")
sns.pairplot(df[["age","income","score"]])
Style rules
- Label everything — title, axes, units.
- Use color intentionally — brand color for the series in focus, grey for the rest.
- Never rely on color alone — colorblind-safe palettes (
viridis,cividis). - Sort bars by value, not alphabetical — makes ranking readable.
- Use log scale when values span orders of magnitude.
Where to next
- plotly for interactive HTML charts (great for reports + notebooks).
- altair for a grammar-of-graphics style declarative API.
Try it
- Make a bar chart with the tallest bar in your brand color and the rest grey.
- Overlay a rolling mean line on top of a daily scatter.
Practice
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
Progress0 / 3
- Exercise 1
Draw a bar chart of categories ['A', 'B', 'C'] with heights [10, 20, 30], then save the figure to an in-memory PNG using io.BytesIO. Assign the raw bytes to a variable named 'png_bytes'.
- Exercise 2
Build a 5-column DataFrame 'df' with 20 rows of numeric data, compute its 5x5 correlation matrix as 'corr', and print the correlation of the first column with itself (df.columns[0] vs df.columns[0]) rounded to 2 decimals as 'self_corr'.
- Exercise 3
Create a scatter plot of 100 random (x, y) points using plt.scatter, then grab the current figure with plt.gcf() and store it in 'fig'. The checker verifies fig has at least one axis with plotted data.