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).

5 min readUpdated 2026-11-30
In This Lesson
  • 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()).
python
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

  1. figsize=(8, 4.5): Sets an explicit 16:9-friendly aspect ratio in inches so text isn't squished.
  2. ax.spines["top"].set_visible(False): Removes the distracting top/right bounding box so eyes focus on the data line.
  3. fig.tight_layout(): Automatically pads margins so rotated x-axis labels or long titles never get clipped when exporting .png or .svg.
  4. plt.close(fig): Critical in automation scripts! Frees figure RAM after saving—if you export 500 charts in a loop without plt.close(fig), Python leaks memory until it crashes.
Watch Out for Memory Leaks in Chart Loops

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:

python
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 FunctionAnalytical PurposeKey Parameters
sns.histplot(data=df, x="latency", kde=True, ax=ax)Inspect distribution shape, peaks, and skewbins=, hue=, kde=True
sns.boxplot(data=df, x="track", y="hours", ax=ax)Compare median, quartiles (IQR), and outliers across groupsx=, y=, hue=
sns.barplot(data=df, x="cat", y="amount", estimator="sum", ax=ax)Compare category totals or means with error barsestimator="sum", errorbar=None
sns.lineplot(data=df, x="date", y="signups", hue="tier", ax=ax)Track multiple series trends over timehue=, marker="o"
sns.scatterplot(data=df, x="hours", y="score", ax=ax)Spot correlations, clusters, and anomalieshue=, alpha=0.7
sns.heatmap(corr_matrix, annot=True, cmap="coolwarm", ax=ax)Visualize numeric correlations or pivot tablesannot=True, fmt=".2f"
Customize Every Seaborn Chart With ax=ax

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:

Python 3Try It Live: Proportional CLI Bar Chart & Histogram
Output

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

Check Your Understanding

What does fig.tight_layout() do before fig.savefig('chart.png')?

Check Your Understanding

Which Seaborn plot best compares the median, quartiles, and outliers of order amounts across 4 product categories?

Check Your Understanding

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?