Python Master Course V2 — 125. Exploratory Data Analysis and Visualization
What you will be able to do
- Match plots to variable types and analysis questions
- Detect skew, outliers and misleading scales
- Separate exploratory observations from causal claims
Prerequisites: 123–124: pandas and clean data; 121: numeric summaries.
Your local workspace
Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson125, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.
Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.
python -m pip install numpy pandas matplotlibThe examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.
Choose a question before choosing a chart
Exploratory data analysis combines summaries and visual inspection to understand a dataset and generate questions. It is useful before modeling because it can reveal missingness, implausible values, skew, different subgroup distributions and relationships that a single average hides. Exploration is not a license to make causal claims or repeatedly search until an attractive pattern appears.
Match the plot to the question. A histogram shows a numerical distribution, with conclusions affected by bin choices. A scatterplot shows relationships between two numerical variables. A grouped dot or bar summary compares categories, but should retain sample sizes and avoid hiding all within-group variation. A time plot needs a meaningful ordered time axis; connecting unrelated categories with a line can imply an order that does not exist.
The mean responds strongly to extreme values; the median describes the middle of the ordered observations. Neither is universally better. A long delivery may be a real operational event, a recording error or an unusual route. Flag it, check provenance and explain any exclusion. Removing it merely because it makes the average less flattering is not a defensible cleaning rule.
Axes carry meaning. Label units, show an appropriate scale and disclose transformations. A bar chart with a truncated vertical baseline exaggerates differences because viewers compare lengths. A scatterplot can reasonably zoom its axes when the range is clear, but should not hide relevant observations. Colors should be distinguishable and reinforced by labels or marker choices. Include a text summary so the main findings do not depend on seeing a chart.
A small synthetic delivery dataset
import pandas as pd
deliveries = pd.DataFrame({
"route": ["A"] * 4 + ["B"] * 4,
"distance_km": [1, 2, 3, 4, 1, 2, 3, 4],
"minutes": [8, 11, 14, 17, 10, 13, 16, 35],
})
print(f"mean minutes: {deliveries['minutes'].mean():.1f}")
print(f"median minutes: {deliveries['minutes'].median():.1f}")
summary = deliveries.groupby("route", sort=True)["minutes"].agg(
count="size", mean="mean", median="median", minimum="min", maximum="max"
)
print(summary[["count", "mean"]].to_dict("index"))Expected output
mean minutes: 15.5
median minutes: 13.5
{'A': {'count': 4, 'mean': 12.5}, 'B': {'count': 4, 'mean': 18.5}}All eight observations are artificial teaching data. Route B has one 35-minute delivery that raises its mean. That does not prove route B is intrinsically slower: route assignment, traffic, package handling and other omitted factors could differ. This dataset is too small to support broad operational conclusions.
Create three plots with clear labels and a text alternative
Append this block to eda.py and run python eda.py. The Agg backend writes a PNG without requiring a desktop display. The script creates its own output directory and never reads an undisclosed file. Each subplot answers a different question, and the shared title states that the data is synthetic.
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
output = Path("output")
output.mkdir(exist_ok=True)
fig, axes = plt.subplots(1, 3, figsize=(14, 4), constrained_layout=True)
axes[0].hist(deliveries["minutes"], bins=[0, 10, 20, 30, 40],
edgecolor="white", color="#2563eb")
axes[0].set(title="Delivery-time distribution", xlabel="Time (minutes)",
ylabel="Number of deliveries")
for route, marker, color in [("A", "o", "#2563eb"), ("B", "s", "#c2410c")]:
rows = deliveries.loc[deliveries["route"] == route]
axes[1].scatter(rows["distance_km"], rows["minutes"],
label=f"Route {route}", marker=marker, color=color)
axes[1].set(title="Distance and duration", xlabel="Distance (km)",
ylabel="Time (minutes)")
axes[1].legend()
axes[2].bar(summary.index, summary["mean"], color=["#2563eb", "#c2410c"])
axes[2].set(title="Mean by route (4 deliveries each)", xlabel="Route",
ylabel="Mean time (minutes)", ylim=(0, 25))
fig.suptitle("Synthetic delivery EDA: descriptive, not causal")
fig.savefig(output / "delivery_eda.png", dpi=150)
plt.close(fig)
text = (
"Eight synthetic deliveries: mean 15.5 minutes, median 13.5 minutes.\n"
"Route A: n=4, mean=12.5. Route B: n=4, mean=18.5.\n"
"A 35-minute Route B observation raises its average.\n"
"The scatterplot shows longer times at larger distances in this sample.\n"
"No causal or population-level conclusion is established.\n"
)
(output / "summary.txt").write_text(text, encoding="utf-8")
print("Created output/delivery_eda.png and output/summary.txt")Expected output
Created output/delivery_eda.png and output/summary.txtThe full script prints the numerical summary first, followed by this final creation line. Inspect the PNG visually after running: check title clipping, legibility, legend labels, units and whether every point is visible. File creation alone does not establish that a chart communicates well.
Guided lab: challenge the first visual impression
Change the histogram bins to intervals of five minutes and compare its appearance. The underlying observations do not change, but the shape can look more or less clustered. Report a pattern only when it survives reasonable presentation choices or explain the sensitivity. With eight points, displaying individual observations alongside summaries is often more informative than a smooth density curve.
Calculate Route B's mean with and without the 35-minute observation as a sensitivity analysis, clearly labeling the exclusion as hypothetical. Do not replace the main result unless you have a defensible data-quality reason. Compare the mean and median to understand how much the single point influences your impression.
Add the raw points over the grouped means or use a boxplot with the individual points. Avoid presenting standard deviation as if it were a confidence interval: spread of individual deliveries and uncertainty of an estimated mean answer different questions. Formal uncertainty will be introduced in Lesson 127.
Write three short statements: one direct observation, one plausible explanation to investigate and one claim the data cannot support. For example, “Route B has a higher sample mean” is observed; “traffic caused the difference” is an untested explanation. Keep that distinction visible in any report accompanying the chart.
Common ways an attractive chart can mislead
A chart can be technically correct and still imply too much. Omitting sample sizes makes a mean from four observations look comparable to one from thousands. Sorting categories by outcome may be useful for comparison but should not be mistaken for time. Using different vertical scales for side-by-side charts can exaggerate or conceal differences. State why a scale or transformation was chosen.
Never infer missing categories have zero observations unless the collection process establishes that fact. An absent route may simply be outside the sample. Keep the data-generation code with the chart, and ensure a rerun regenerates the same values. For real data, preserve access permissions and provenance; this lesson avoids those complications by using an explicit synthetic table.
Questions worth asking
Why is a histogram not the same as a bar chart?
A histogram bins a numerical variable into intervals; adjacent bins represent ranges on a numerical scale. A categorical bar chart compares separate categories. Bin width affects a histogram's appearance, while category definitions determine a bar chart's grouping.
Should the 35-minute delivery be deleted as an outlier?
Not automatically. It may be a valid rare event and could be operationally important. Investigate provenance, define a defensible rule and report sensitivity. Deleting it because it changes the average would bias the narrative.
Why does the route chart start at zero?
Bar lengths encode magnitude, so a truncated baseline can exaggerate relative differences. Starting at zero supports honest length comparison. Other plot types may use a zoomed range if their axes and purpose are clear.
Does the scatterplot establish that distance causes longer delivery time?
No. It shows an association in a tiny synthetic dataset. Causal interpretation requires assumptions or a design that addresses alternative explanations. Distance may be relevant, but the visual pattern alone cannot establish a causal effect.
Why include a non-graphical summary?
It improves accessibility and makes the central quantities and limitations available without interpreting the image. It also forces the analyst to articulate the actual evidence rather than relying on an impressive-looking chart to carry an ambiguous claim.
Are error bars mandatory on every EDA chart?
No, but their meaning must be clear when used. Standard deviation, standard error and confidence intervals describe different things. A descriptive chart of eight raw points can be more honest than adding an unexplained uncertainty decoration.
Practice, then compare your solution
1. Sensitivity calculation
What is Route B's mean after hypothetically excluding 35?
Worked solution and reasoning
The remaining values are 10, 13 and 16, whose mean is 13.0 minutes. Report that as a sensitivity result, not as a corrected dataset unless an independent reason establishes that 35 is invalid.
2. Separate evidence from story
Rewrite “Route B causes a six-minute delay.”
Worked solution and reasoning
“In these eight synthetic observations, Route B's sample mean is 6.0 minutes higher than Route A's. The comparison is descriptive and does not establish a causal route effect.” This preserves the calculation while limiting the conclusion.
Mastery checkpoint
Deliver three labeled plots, a text summary and the code that creates the synthetic data. Explain each visual choice, retain the unusual observation and distinguish descriptive findings from explanations that need further evidence.
Official documentation and next steps
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.