What You Will Learn
- How to make a bar, line, histogram, and scatter plot from a DataFrame
- The one-line pandas plotting syntax
- When to use each chart type
- How to save charts as image files
Why This Topic Matters
Numbers in a table are hard to read. The same numbers in a bar chart take 2 seconds to understand. Visualization is not decoration — it is the fastest way for a human brain to extract meaning from data. pandas has built-in plotting that wraps matplotlib, so you can chart a DataFrame with one line of Python.
Setup
import pandas as pd
import matplotlib.pyplot as plt
# Make plots appear inline in Jupyter
%matplotlib inline
# Optional: larger, nicer default style
plt.rcParams["figure.figsize"] = (8, 5)
plt.rcParams["font.size"] = 12
%matplotlib inline is a Jupyter magic — only needed in notebooks, not in scripts.
Sample Data
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"revenue": [12000, 13500, 15000, 14800, 16200, 17000,
18500, 19000, 17800, 16500, 15200, 14000],
"orders": [120, 135, 148, 145, 160, 168,
182, 188, 175, 162, 150, 138],
"avg_order":[100, 100, 101, 102, 101, 101,
102, 101, 102, 102, 101, 101]
})
df = df.set_index("month")
1. Bar Chart — Comparing Categories
df["revenue"].plot(kind="bar", color="steelblue", title="Monthly Revenue")
plt.ylabel("Revenue (₹)")
plt.tight_layout()
plt.savefig("revenue_bar.png", dpi=120)
plt.show()
Use a bar chart when: you want to compare values across discrete categories (months, cities, products). Each bar's height encodes one number.
Avoid when: the categories are ordered and continuous (use a line) or when there are more than ~15 categories (rotate labels or aggregate).
Horizontal bar — for long category labels
df["revenue"].plot(kind="barh", color="steelblue")
Horizontal bars are easier to read when category names are long (e.g., full product names).
2. Line Chart — Trends Over Time
df["revenue"].plot(kind="line", marker="o", color="darkgreen",
title="Monthly Revenue Trend")
plt.ylabel("Revenue (₹)")
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("revenue_line.png", dpi=120)
plt.show()
Use a line chart when: the x-axis is ordered and continuous (time, distance, sequence). Lines connect points, making trends obvious.
Avoid when: the x-axis is categorical with no inherent order (use a bar).
Multiple lines on one chart
df[["revenue", "orders"]].plot(kind="line", marker="o")
plt.title("Revenue and Orders Over Time")
plt.grid(True, alpha=0.3)
When plotting two columns with very different scales (revenue in thousands, orders in hundreds), use a secondary y-axis:
ax = df["revenue"].plot(kind="line", color="darkgreen", label="revenue")
ax2 = df["orders"].plot(kind="line", secondary_y=True,
color="darkorange", label="orders")
ax.set_ylabel("Revenue (₹)")
ax2.set_ylabel("Orders")
ax.legend(loc="upper left")
ax2.legend(loc="lower right")
plt.title("Revenue and Orders Over Time")
3. Histogram — Distribution of a Numeric Column
df["avg_order"].plot(kind="hist", bins=5, color="purple",
edgecolor="white", title="Distribution of Avg Order Value")
plt.xlabel("Avg Order Value (₹)")
plt.tight_layout()
plt.show()
Use a histogram when: you want to see the shape of a numeric column — where values cluster, whether the distribution is symmetric or skewed, whether there are outliers.
Avoid when: the column is categorical (use a bar chart of value counts).
Choosing the number of bins
- Too few bins (e.g., 3): the histogram hides detail.
- Too many bins (e.g., 50): the histogram is noisy.
- Rule of thumb: start with the square root of the number of rows.
bins=int(len(df)**0.5).
4. Scatter Plot — Relationship Between Two Numeric Columns
df.plot(kind="scatter", x="orders", y="revenue",
color="crimson", alpha=0.6,
title="Orders vs Revenue")
plt.tight_layout()
plt.show()
Use a scatter plot when: you want to see whether two numeric variables are related. A cloud going up-and-to-the-right suggests positive correlation. A flat cloud suggests no relationship.
Avoid when: you have too many points (they overlap into a blob — use a hexbin or sample the data).
Which Chart to Use — Quick Decision Guide
| Question | Chart |
|---|---|
| How do categories compare? | Bar |
| How does a value change over time? | Line |
| What is the distribution of one variable? | Histogram |
| Are two numeric variables related? | Scatter |
| How is a categorical column distributed? | Bar chart of value_counts() |
| How do parts make up a whole? | Stacked bar (rarely pie) |
We cover chart selection in depth in lesson 33 and dashboard design in lesson 34.
Styling Tips That Matter
- Always add a title. A chart without a title is a Rorschach test.
- Label both axes. "Revenue (₹)" beats "revenue".
- Use
plt.tight_layout()before saving. Otherwise labels get clipped. - One accent color. Default matplotlib colors are fine; do not rainbow-ize.
- Remove chart junk. If gridlines, borders, and legends are not helping, drop them.
Saving Charts as Files
plt.savefig("revenue.png", dpi=120, bbox_inches="tight")
dpi=120 is sharp enough for screens and most documents. Use 300 for print-quality. bbox_inches="tight" prevents labels from being cut off.
One-Chart-Per-Cell Rule
In Jupyter, each plt.show() ends a chart. If you forget it, charts merge. Always call plt.show() at the end of each chart cell, or use plt.figure() to start a new figure explicitly.
Common Mistakes
- Using a pie chart for many categories. Past 4–5 slices, pies are unreadable. Use a bar chart.
- Defaulting to line charts for categorical data. Lines imply continuous order. Use bars for unordered categories.
- Forgetting
plt.tight_layout(). Results in clipped titles and axis labels in saved images. - Plotting two columns with very different scales on the same axis. One line goes flat. Use
secondary_y=True. - Using too many bins in a histogram. Produces a noisy chart that hides the shape.
- Not sorting category data before plotting. Bars appear in DataFrame row order, which may be arbitrary. Sort first:
df.sort_values("revenue", ascending=False).plot(kind="bar").
Practical Exercise (20 minutes)
- Create the sample DataFrame above.
- Plot monthly revenue as a bar chart. Save it as
revenue_bar.png. - Plot monthly revenue as a line chart with markers. Save it as
revenue_line.png. - Plot a histogram of
avg_order. Try 3, 5, and 10 bins. Which shows the shape best? - Plot a scatter of orders vs revenue. Describe the relationship in one sentence.
- Bonus: plot revenue and orders on the same chart with a secondary y-axis.
Mini Challenge
Load any CSV with at least 3 numeric columns. Make a bar chart of one column, a line chart of another, a histogram of the third, and a scatter of two of them. Save all four as PNGs. Pick the one chart that tells the most interesting story and write a one-paragraph caption explaining it.
Key Takeaways
df["col"].plot(kind="bar"|"line"|"hist")— one-line charts in pandas.- Bar = compare categories; Line = trend over time; Histogram = distribution; Scatter = relationship.
- Always add a title, label axes, and call
plt.tight_layout(). - Save with
plt.savefig("name.png", dpi=120, bbox_inches="tight"). - Use
secondary_y=Truewhen plotting two columns with very different scales.
Previously learned: Phase 5 (lessons 24–27) covered pandas from setup through cleaning.
Today: You turned DataFrames into charts.
Next: Phase 5 is complete. Phase 6 begins with lesson 29 — Mean, Median, and Mode, the first of four statistics lessons.
FAQ
Should I use matplotlib, seaborn, or plotly?
matplotlib — the foundation; everything else builds on it. Learn it first.
seaborn — prettier statistical charts (boxplots, heatmaps, regression plots). Use when matplotlib feels too manual.
plotly — interactive charts for web dashboards. Use when you need hover/zoom, not for static reports.
Why do my charts look different in scripts vs Jupyter?
Jupyter auto-displays charts when a cell ends. In a script, you must call plt.show() to see them, or plt.savefig() to write them to a file. Also, Jupyter applies its own default style; scripts use matplotlib defaults.
Comments
Comments
Post a Comment