Rana Maninder Singh
Lesson 8 of 12Data Analysis with Python

EDA Data Visualization

Lesson opener

In one line: Univariate, bivariate, multivariate exploration.

Why it matters: A bar chart on counts answers "how many orders per customer type?" - the second univariate view after numeric distribution.

Before this lesson: Pandas & Excel

Before you start

ResourceLink
PreviousPandas & Excel
NextMatplotlib


What you will learn

Univariate, bivariate, multivariate exploration.

Python EDA cheat sheet — Pandas and Seaborn commands
Python EDA cheat sheet — Pandas and Seaborn commands

Univariate

[Univariate EDA plots]

WHY Histogram and boxplot show spread and outliers on one variable — start every EDA here.

WHEN Run on order_total or revenue before comparing to anything else.

import pandas as pd  # table tool for columns and rows
import matplotlib.pyplot as plt  # charting library

# One table: product orders (one numeric column to study = order_total)
orders = pd.DataFrame({
    "product": ["Desk Lamp", "Office Chair", "Desk Lamp", "Monitor", "Office Chair", "Keyboard"],
    "order_total": [45, 320, 52, 410, 298, 89],
    "department": ["Retail", "Corporate", "Retail", "Corporate", "Corporate", "Retail"],
})

# Histogram — how order totals are spread (single variable)
plt.figure(figsize=(6, 4))  # new blank chart, 6×4 inches
plt.hist(orders["order_total"], bins=5, edgecolor="black")  # count orders in each price band
plt.title("Distribution of order totals")  # chart title for slides
plt.xlabel("Order total (USD)")  # horizontal axis label
plt.ylabel("Number of orders")  # vertical axis label
plt.tight_layout()  # reduce clipped labels
plt.savefig("outputs/ds9_univariate_hist.png")  # save PNG for reports
plt.show()  # display in notebook or script window

# Box plot — median, quartiles, and outliers for the same column
plt.figure(figsize=(4, 4))
plt.boxplot(orders["order_total"], vert=True)  # one box summarizing the column
plt.title("Order totals — median and spread")
plt.ylabel("Order total (USD)")
plt.tight_layout()
plt.savefig("outputs/ds9_univariate_box.png")
plt.show()

# Summary numbers analysts quote in meetings
print("Mean:", round(orders["order_total"].mean(), 2))  # average order value
print("Median:", orders["order_total"].median())  # middle order (outlier-resistant)
print("Min:", orders["order_total"].min())  # smallest order
print("Max:", orders["order_total"].max())  # largest order

Breaking it down:

Use this when: someone asks 'what does a typical order look like?' before any cross-variable analysis.

What this tells you in real life: If the mean is much higher than the median, a few large orders (like monitors) are pulling the average up — you would investigate big-ticket products separately instead of treating every order as “typical.”

[Count by segment — bar chart]

WHY: A bar chart on counts answers "how many orders per customer type?" — the second univariate view after numeric distribution.

WHEN: Marketing asks which segment drives volume before comparing revenue.

segment_counts = orders.groupby("department")["product"].count()
plt.figure(figsize=(5, 4))
plt.bar(segment_counts.index, segment_counts.values, color=["#2563eb", "#e85d6a"])
plt.title("Order count by department")
plt.xlabel("Department")
plt.ylabel("Number of orders")
plt.tight_layout()
plt.savefig("outputs/ds9_segment_bar.png")
plt.show()
print(segment_counts)

Breaking it down:

Use this when: the question is categorical ("Retail vs Corporate") not numeric.


Bivariate

[Bivariate scatter and corr]

WHY Scatter shows relationship; corr gives one summary number — neither proves causation.

WHEN Use when testing if spend tracks revenue.

import pandas as pd  # table tool
import matplotlib.pyplot as plt  # charts

# Same business table — two numeric columns to compare
campaigns = pd.DataFrame({
    "product_line": ["Lamps", "Chairs", "Monitors", "Keyboards", "Chairs", "Monitors"],
    "marketing_spend": [1200, 3400, 5100, 900, 2800, 4600],
    "sales_revenue": [4800, 9200, 18500, 2100, 8100, 16200],
})

# Scatter — does higher spend link to higher revenue?
plt.figure(figsize=(6, 4))
plt.scatter(campaigns["marketing_spend"], campaigns["sales_revenue"], color="steelblue")
plt.title("Marketing spend vs sales revenue")
plt.xlabel("Marketing spend (USD)")  # x = money spent on ads
plt.ylabel("Sales revenue (USD)")  # y = revenue earned
plt.tight_layout()
plt.savefig("outputs/ds9_bivariate_scatter.png")
plt.show()

# Correlation — one number from -1 (opposite) to +1 (same direction)
r = campaigns["marketing_spend"].corr(campaigns["sales_revenue"])
print(f"Correlation (spend vs revenue): {r:.2f}")

Breaking it down:

Use this when: marketing wants to know if higher ad spend links to higher sales (with caveats).

What this tells you in real life: A strong positive correlation suggests spend and revenue move together — but it does not prove spend caused sales. An analyst would check seasonality and run a controlled test before increasing the marketing budget.


Multivariate

[Multivariate heatmap and scatter]

WHY Heatmap for numeric correlations; colored scatter adds a third dimension (region).

WHEN Use when one bivariate chart hides segment differences.

import pandas as pd
import matplotlib.pyplot as plt

# Three numeric columns + one category (region) for colour
stores = pd.DataFrame({
    "region": ["North", "South", "North", "West", "South", "West", "North", "South"],
    "marketing_spend": [800, 1200, 950, 1500, 1100, 1400, 900, 1300],
    "sales_revenue": [4200, 5100, 4600, 7200, 5800, 6900, 4400, 5500],
    "order_count": [120, 95, 110, 180, 102, 165, 115, 98],
})

# Heatmap — strength of relationships between all numeric columns
numeric = stores[["marketing_spend", "sales_revenue", "order_count"]]  # drop region for corr matrix
corr = numeric.corr()  # correlation table (3×3)
plt.figure(figsize=(5, 4))
plt.imshow(corr, cmap="Blues", vmin=-1, vmax=1)  # colour grid by correlation strength
plt.colorbar(label="Correlation")
plt.xticks(range(3), corr.columns, rotation=45, ha="right")
plt.yticks(range(3), corr.columns)
plt.title("Correlation heatmap (3 variables)")
for row in range(3):
    for col in range(3):
        plt.text(col, row, f"{corr.iloc[row, col]:.2f}", ha="center", va="center")  # label each cell
plt.tight_layout()
plt.savefig("outputs/ds9_multivariate_heatmap.png")
plt.show()

# Scatter coloured by region — same two axes, category adds a third dimension
regions = stores["region"].unique()
colors = {"North": "tab:blue", "South": "tab:orange", "West": "tab:green"}
plt.figure(figsize=(6, 4))
for region in regions:
    subset = stores[stores["region"] == region]  # one region at a time
    plt.scatter(
        subset["marketing_spend"],
        subset["sales_revenue"],
        label=region,
        color=colors.get(region, "gray"),
    )
plt.title("Spend vs revenue by region")
plt.xlabel("Marketing spend (USD)")
plt.ylabel("Sales revenue (USD)")
plt.legend(title="Region")  # legend explains colours
plt.tight_layout()
plt.savefig("outputs/ds9_multivariate_scatter_region.png")
plt.show()

Breaking it down:

Use this when: North and South look similar until you color by region.

What this tells you in real life: Use multivariate views when one chart is not enough — for example, North and South may look similar on spend vs revenue until colour by region shows West stores convert spend into higher revenue per dollar. That is when you drill into regional pricing or staffing, not just total spend.


EDA checklist

  1. Row count and keys
  2. Missing %
  3. Outliers
  4. One relationship
  5. One business question answered

Document in notebook markdown cells.


Essential commands

Command / actionWhat it does
df.describe()Numeric summary statistics.
df.value_counts()Frequency of categorical values.
df.corr()Correlation matrix for numeric columns.

Practice

Do this now: Notebook section per EDA type; 3 written insights; link to Matplotlib.

Checklist

  • [ ] uni/bi/multi done
  • [ ] 3 insights written
  • [ ] ready for charts