4. Data Visualization & Storytelling
Visualizing Trends & Distributions with Matplotlib & Seaborn
Create clean, publication-ready charts in Python using Matplotlib's object-oriented API (fig, ax) and Seaborn statistical plots (histplot, barplot, lineplot, boxplot).
- Use Matplotlib's object-oriented fig, ax = plt.subplots() API cleanly
- Build bar, line, histogram, and scatter plots with clear labels, titles, and saved PNG exports
- Create clean statistical visualizations rapidly with Seaborn
Imagine sending a 40-row Pandas summary table to a product manager before a launch review. They stare at numbers for two minutes—whereas a crisp chart reveals a weekend traffic drop or a skewed latency tail in two seconds.
Python's plotting ecosystem rests on two layered libraries: Matplotlib (the foundational drawing engine) and Seaborn (a high-level statistical wrapper built on top of Matplotlib that speaks Pandas DataFrames natively).
1. Matplotlib's Object-Oriented API (fig, ax)
Tutorials often show quick plt.plot(...) / plt.title(...) shortcuts. Those use a hidden global state ("currently active chart") that breaks down the moment your script generates two charts, multi-panel dashboards, or automated weekly PNGs!
Always use Matplotlib's object-oriented API—fig, ax = plt.subplots(...):
fig(Figure): The outer canvas or image file (figsize,tight_layout(),savefig()).ax(Axes): The individual plot box inside the canvas (ax.plot(),ax.set_title(),ax.set_ylabel(),ax.grid()).
import matplotlib.pyplot as plt
months = ["Aug", "Sep", "Oct", "Nov"]
revenue = [12400, 15800, 14900, 19200]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(months, revenue, marker="o", linewidth=2.5, color="#4f46e5")
ax.set_title("Monthly Revenue Growth (2026)", fontsize=14, fontweight="bold", pad=12)
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (USD)")
ax.set_ylim(bottom=0)
ax.grid(axis="y", linestyle="--", alpha=0.4)
# Remove cluttered top and right chart borders
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
fig.tight_layout()
fig.savefig("monthly_revenue.png", dpi=150)
plt.close(fig)Line-by-Line Walkthrough of Publication Polish
figsize=(8, 4.5): Sets an explicit 16:9-friendly aspect ratio in inches so text isn't squished.ax.spines["top"].set_visible(False): Removes the distracting top/right bounding box so eyes focus on the data line.fig.tight_layout(): Automatically pads margins so rotated x-axis labels or long titles never get clipped when exporting.pngor.svg.plt.close(fig): Critical in automation scripts! Frees figure RAM after saving—if you export 500 charts in a loop withoutplt.close(fig), Python leaks memory until it crashes.
When generating per-customer or per-region charts inside a for loop, always call plt.close(fig) right after fig.savefig(...). Matplotlib keeps every open Figure alive in memory until explicitly closed!
2. Multi-Panel Dashboards (plt.subplots(1, 2))
Because ax is just a variable, creating side-by-side comparisons takes one argument:
fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(12, 4.5))
ax_left.bar(categories, totals, color="#4f46e5")
ax_left.set_title("Total Revenue by Category")
ax_right.hist(latencies_ms, bins=25, color="#0ea5e9", edgecolor="white")
ax_right.set_title("API Latency Distribution (ms)")
fig.tight_layout()3. Fast Statistical Plots with Seaborn
Seaborn (import seaborn as sns) automates grouping, confidence intervals, color palettes, and DataFrame column binding—while letting you plug straight into Matplotlib's ax=:
| Seaborn Function | Analytical Purpose | Key Parameters |
|---|---|---|
sns.histplot(data=df, x="latency", kde=True, ax=ax) | Inspect distribution shape, peaks, and skew | bins=, hue=, kde=True |
sns.boxplot(data=df, x="track", y="hours", ax=ax) | Compare median, quartiles (IQR), and outliers across groups | x=, y=, hue= |
sns.barplot(data=df, x="cat", y="amount", estimator="sum", ax=ax) | Compare category totals or means with error bars | estimator="sum", errorbar=None |
sns.lineplot(data=df, x="date", y="signups", hue="tier", ax=ax) | Track multiple series trends over time | hue=, marker="o" |
sns.scatterplot(data=df, x="hours", y="score", ax=ax) | Spot correlations, clusters, and anomalies | hue=, alpha=0.7 |
sns.heatmap(corr_matrix, annot=True, cmap="coolwarm", ax=ax) | Visualize numeric correlations or pivot tables | annot=True, fmt=".2f" |
Create fig, ax = plt.subplots(figsize=(8, 4)), pass ax=ax into any Seaborn call (sns.boxplot(data=df, x="track", y="hours", ax=ax)), and finish with ax.set_title(...), fig.tight_layout(), and fig.savefig(...). You get Seaborn's speed with Matplotlib's pixel-level control!
Try It Yourself in the Playground
You can render crisp proportional bar charts and distribution histograms directly inside terminal/Python scripts using Unicode block bars—run and customize this reusable CLI chart builder below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why is fig, ax = plt.subplots() preferred over calling plt.title(...) and plt.plot(...) directly in reusable report scripts?
Quick Checkpoints
What does fig.tight_layout() do before fig.savefig('chart.png')?
Which Seaborn plot best compares the median, quartiles, and outliers of order amounts across 4 product categories?
Your scheduled script exports 300 daily PNG charts in a for loop and crashes with an Out-Of-Memory error. Which Matplotlib line is likely missing?