Matplotlib Tutorial

📊 Complete Matplotlib Master Tutorial (Beginner → Advanced)


🧠 1️⃣ What is Matplotlib?

Matplotlib is the core Python visualization library used for:

  • Data analysis

  • Machine learning evaluation

  • Research plots

  • Business dashboards

  • Financial charts

Main module:

import matplotlib.pyplot as plt

🟢 2️⃣ Basic Plot (Foundation)

import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [10,20,25,30,40]

plt.plot(x, y)
plt.title("Basic Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()

When to use?

  • Trends

  • Time series

  • ML loss curves


🔵 3️⃣ Line Customization (Professional Style)

plt.plot(x, y,
         color="blue",
         linestyle="--",
         marker="o",
         linewidth=2)

plt.grid(True)
plt.show()

Important parameters:

  • color

  • linestyle

  • marker

  • linewidth

  • alpha (transparency)


🟡 4️⃣ Bar Chart (Category Comparison)

names = ["Hari", "Rahul", "Amit"]
salary = [50000, 60000, 55000]

plt.bar(names, salary)
plt.title("Salary Comparison")
plt.show()

Used for:

  • Feature importance

  • Sales per region

  • Categorical comparison


🟠 5️⃣ Histogram (VERY IMPORTANT FOR ML 🔥)

import numpy as np

data = np.random.randn(1000)

plt.hist(data, bins=30)
plt.title("Distribution")
plt.show()

Why important?

  • Check normal distribution

  • Feature engineering

  • Outlier detection


🔴 6️⃣ Scatter Plot (Correlation)

x = np.random.rand(100)
y = np.random.rand(100)

plt.scatter(x, y)
plt.title("Scatter Plot")
plt.show()

Used for:

  • Correlation check

  • Regression visualization

  • Feature relationship


🟣 7️⃣ Subplots (Professional Dashboards)

fig, ax = plt.subplots(2, 2, figsize=(8,6))

ax[0,0].plot(x, y)
ax[0,0].set_title("Plot 1")

ax[0,1].hist(data)
ax[0,1].set_title("Histogram")

ax[1,0].bar(names, salary)
ax[1,0].set_title("Bar")

ax[1,1].scatter(x, y)
ax[1,1].set_title("Scatter")

plt.tight_layout()
plt.show()

Used in:

  • ML reporting

  • EDA dashboards


🟤 8️⃣ Object-Oriented API (Senior Level 🔥)

Instead of using plt everywhere:

fig, ax = plt.subplots()

ax.plot(x, y)
ax.set_title("Professional Plot")
ax.set_xlabel("X")
ax.set_ylabel("Y")

plt.show()

Why better?

  • Cleaner

  • Scalable

  • More control

Interviewers LOVE this.


⚫ 9️⃣ Real ML Example (Loss Curve)

epochs = [1,2,3,4,5]
train_loss = [0.8, 0.6, 0.5, 0.4, 0.35]
val_loss = [0.85, 0.65, 0.55, 0.5, 0.48]

plt.plot(epochs, train_loss, label="Train")
plt.plot(epochs, val_loss, label="Validation")

plt.legend()
plt.title("Training vs Validation Loss")
plt.show()

🔥 🔟 Confusion Matrix (ML Interview Important)

cm = np.array([[50, 5],
               [3, 42]])

plt.imshow(cm, cmap="Blues")
plt.colorbar()
plt.title("Confusion Matrix")
plt.show()

🟢 1️⃣1️⃣ Save High Quality Image

plt.savefig("plot.png", dpi=300)

🟡 1️⃣2️⃣ Time Series Example

import pandas as pd

dates = pd.date_range("2024-01-01", periods=10)
values = np.random.randint(100,200,10)

plt.plot(dates, values)
plt.xticks(rotation=45)
plt.show()

Used in:

  • Stock market

  • Sales growth

  • Forecasting


🔵 1️⃣3️⃣ Performance & Best Practices

✔ Use object-oriented API
✔ Use tight_layout()
✔ Avoid plotting inside loops
✔ Use NumPy arrays
✔ Keep labels readable


🧠 1️⃣4️⃣ Most Asked Interview Questions

  1. Difference between plt.plot and ax.plot?

  2. What is tight_layout?

  3. Difference between scatter and plot?

  4. How to plot large datasets efficiently?

  5. How to create multiple subplots?

  6. What is figure and axis?


🚀 1️⃣5️⃣ Matplotlib Workflow for ML Project

Real pipeline:

  1. Load dataset (Pandas)

  2. Plot distribution (hist)

  3. Check correlation (scatter)

  4. Plot model performance

  5. Plot confusion matrix

  6. Save report


I’ll build a full “Sales Analysis Dashboard” using Pandas + Matplotlib step by step.

You can run this in Jupyter / Colab / VS Code as-is.


🧩 Project: Sales Data Analysis & Visualization (End-to-End)

🎯 Goal

You are a data analyst / ML engineer. You got a sales CSV file and need to:

  • Understand revenue trend over time

  • Compare sales by product category

  • Find top products

  • Visualize relationship between quantity & revenue

  • Show monthly trend (like real business reporting)

We’ll simulate the dataset in code (so you don’t need any external file) and then visualize it.


1️⃣ Setup & Sample Data

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# For better looking plots (optional)
plt.style.use("ggplot")

Create a fake sales dataset (like CSV data):

np.random.seed(42)  # for reproducibility

dates = pd.date_range(start="2024-01-01", periods=120, freq="D")
products = ["Laptop", "Phone", "Tablet", "Headphones", "Smartwatch"]
categories = {
    "Laptop": "Electronics",
    "Phone": "Electronics",
    "Tablet": "Electronics",
    "Headphones": "Accessories",
    "Smartwatch": "Wearables",
}

data = []

for date in dates:
    for _ in range(np.random.randint(5, 15)):  # random orders per day
        product = np.random.choice(products)
        price = {
            "Laptop": 80000,
            "Phone": 40000,
            "Tablet": 30000,
            "Headphones": 4000,
            "Smartwatch": 15000,
        }[product]
        quantity = np.random.randint(1, 5)

        data.append({
            "date": date,
            "product": product,
            "category": categories[product],
            "price": price,
            "quantity": quantity,
            "revenue": price * quantity
        })

df = pd.DataFrame(data)
df.head()

💡 In real life, this would be:

df = pd.read_csv("sales.csv", parse_dates=["date"])

2️⃣ Basic Exploration

print(df.shape)
print(df.info())
print(df.describe(numeric_only=True))

Check first few rows:

df.head()

3️⃣ Total Revenue Over Time (Line Plot)

Business question:
👉 “How is revenue trending daily?”

daily_revenue = df.groupby("date")["revenue"].sum().reset_index()

plt.figure(figsize=(10, 5))
plt.plot(daily_revenue["date"], daily_revenue["revenue"], marker="o")
plt.title("Daily Revenue Trend")
plt.xlabel("Date")
plt.ylabel("Revenue")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

🔍 Use this to see growth / drops / seasonality.


4️⃣ Revenue by Product Category (Bar Chart)

Business question:
👉 “Which category is making the most money?”

category_revenue = df.groupby("category")["revenue"].sum().reset_index()

plt.figure(figsize=(7, 5))
plt.bar(category_revenue["category"], category_revenue["revenue"])
plt.title("Total Revenue by Category")
plt.xlabel("Category")
plt.ylabel("Revenue")
plt.tight_layout()
plt.show()

This is like a classic management dashboard chart.


5️⃣ Top 5 Products by Revenue (Horizontal Bar)

product_revenue = df.groupby("product")["revenue"].sum().sort_values(ascending=False)

top_products = product_revenue.head(5)

plt.figure(figsize=(7, 5))
plt.barh(top_products.index, top_products.values)
plt.title("Top 5 Products by Revenue")
plt.xlabel("Revenue")
plt.gca().invert_yaxis()  # highest on top
plt.tight_layout()
plt.show()

Good for:

  • Product strategy

  • Inventory decisions


6️⃣ Relationship: Quantity vs Revenue (Scatter Plot)

Business question:
👉 “Are orders with more quantity also bringing more revenue?”

# Aggregate per order-like grain: here we'll pretend each row is an order
plt.figure(figsize=(7, 5))
plt.scatter(df["quantity"], df["revenue"], alpha=0.5)
plt.title("Quantity vs Revenue")
plt.xlabel("Quantity")
plt.ylabel("Revenue")
plt.tight_layout()
plt.show()

In real ML, you’d use this kind of plot to:

  • Check relationship between features

  • Spot outliers


7️⃣ Monthly Revenue Trend (Resampling + Line Plot)

Business question:
👉 “How are we performing month over month?”

df["date"] = pd.to_datetime(df["date"])
monthly_revenue = df.set_index("date")["revenue"].resample("M").sum()

plt.figure(figsize=(8, 5))
plt.plot(monthly_revenue.index, monthly_revenue.values, marker="o")
plt.title("Monthly Revenue Trend")
plt.xlabel("Month")
plt.ylabel("Revenue")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

This is exactly what you’d show to:

  • Product manager

  • Business head

  • CEO


8️⃣ Multi-Chart Dashboard with Subplots

Now let’s put multiple views in one figure like a mini-dashboard.

fig, axes = plt.subplots(2, 2, figsize=(12, 8))

# 1) Daily Revenue
axes[0, 0].plot(daily_revenue["date"], daily_revenue["revenue"])
axes[0, 0].set_title("Daily Revenue")
axes[0, 0].tick_params(axis="x", rotation=45)

# 2) Category Revenue
axes[0, 1].bar(category_revenue["category"], category_revenue["revenue"])
axes[0, 1].set_title("Revenue by Category")

# 3) Top Products
axes[1, 0].barh(top_products.index, top_products.values)
axes[1, 0].set_title("Top 5 Products")
axes[1, 0].invert_yaxis()

# 4) Quantity vs Revenue
axes[1, 1].scatter(df["quantity"], df["revenue"], alpha=0.5)
axes[1, 1].set_title("Quantity vs Revenue")

plt.tight_layout()
plt.show()

This is very close to a real analytics dashboard.


9️⃣ Bonus: Moving Average (Smooothed Trend)

You’d often smooth noisy daily revenue.

daily_revenue["rolling_7d"] = daily_revenue["revenue"].rolling(window=7).mean()

plt.figure(figsize=(10, 5))
plt.plot(daily_revenue["date"], daily_revenue["revenue"], label="Daily Revenue", alpha=0.5)
plt.plot(daily_revenue["date"], daily_revenue["rolling_7d"], label="7-Day Moving Avg", linewidth=2)
plt.title("Daily Revenue with 7-Day Moving Average")
plt.xlabel("Date")
plt.ylabel("Revenue")
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

This is gold in ML + analytics interviews.


🔥 What this project shows about you (for interviews / resume)

You can claim:

  • ✅ Experience with EDA using Pandas + Matplotlib

  • ✅ Ability to build dashboards & business visualizations

  • ✅ Understanding of time series, trends, groupby, aggregation

  • ✅ Practical awareness of KPIs (revenue, top products, category performance)



Comments

Popular posts from this blog

Python Tutorial with examples

Machine learning tutorial

RAG (Retrieval-Augmented Generation) tutorial