Pandas Plotting: Charts Straight from DataFrames

Pandas Plotting: Charts Straight from DataFrames in Python: You have a DataFrame. You want to see it.

Concept Explanation

You have a DataFrame. You want to see it. The long route is to pull columns out into lists and hand them to Matplotlib. The short route is one method call:

df.plot()

Pandas wraps Matplotlib and reads structure straight off your DataFrame — the index becomes the x-axis, each column becomes a series, and the column names become the legend. For exploratory work this is the fastest path from data to picture that exists in Python.

Crucially, .plot() returns a Matplotlib Axes object. That means you are never trapped: get the chart in one line, then reach for the full Matplotlib API to polish it.

The Kinds

df.plot(kind="line")     # or the shorthand: df.plot.line()
kindShowsUse for
lineValues over an ordered indexTrends over time (the default)
bar / barhMagnitude per categoryComparing groups
histDistribution of one column"What is the shape of this data?"
boxMedian, quartiles, outliersComparing distributions side by side
scatterTwo columns against each otherCorrelation
areaStacked cumulative valuesComposition over time
pieParts of a wholeRarely — humans read angles badly

The Arguments Worth Memorising

ArgumentEffect
x=, y=Which columns to use (otherwise the index and all columns)
figsize=(10, 5)Size in inches — the fix for a cramped chart
title=Chart title
subplots=TrueOne panel per column instead of all on one axis
stacked=TrueStack bars or areas rather than grouping them
rot=45Rotate tick labels so long category names stay readable
logy=TrueLog-scale the y-axis for data spanning orders of magnitude
ax=Draw onto an existing Axes — this is how you combine charts

The Pattern That Makes This Powerful

Pandas plotting shines when you chain it onto a transformation. The aggregation and the chart become one readable line:

df.groupby("region")["sales"].sum().sort_values().plot.barh()

Group, sum, sort, draw. That single line replaces a dozen lines of manual list-building, and it reads in the order you thought of it.

Time Series Get Special Treatment

With a DatetimeIndex, Pandas formats the axis intelligently and unlocks resample:

df.resample("ME").mean().plot()      # monthly averages from daily data

Code Example #1 (Basic)

From raw data to four different views.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "month":   ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "revenue": [12000, 14500, 13200, 17800, 19100, 21500],
    "costs":   [ 9000,  9400,  9100, 11200, 11800, 12400],
})
df = df.set_index("month")          # the index becomes the x-axis

# 1. Both columns as lines
df.plot(figsize=(9, 4), title="Revenue vs Costs", ylabel="GBP")
plt.tight_layout()
plt.savefig("lines.png", dpi=150)
plt.close()

# 2. Grouped bars
df.plot.bar(figsize=(9, 4), rot=0, title="Monthly Comparison")
plt.tight_layout()
plt.savefig("bars.png", dpi=150)
plt.close()

# 3. A derived column, plotted directly
df["margin"] = df["revenue"] - df["costs"]
df["margin"].plot.area(alpha=0.4, figsize=(9, 4), title="Gross Margin")
plt.tight_layout()
plt.savefig("margin.png", dpi=150)
plt.close()

# 4. One panel per column
df[["revenue", "costs"]].plot(subplots=True, figsize=(9, 6), sharex=True)
plt.tight_layout()
plt.savefig("panels.png", dpi=150)
plt.close()

print(df)

plt.savefig before plt.close() is the habit for scripts; in a Jupyter notebook %matplotlib inline displays them and you can skip both. plt.close() matters in loops — without it, figures accumulate in memory and Matplotlib warns you about it.

Code Example #2 (Intermediate)

Aggregating and polishing — the realistic workflow.

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

rng = np.random.default_rng(42)          # seeded: reproducible output
days = pd.date_range("2024-01-01", periods=180, freq="D")

df = pd.DataFrame({
    "date":     np.repeat(days, 3),
    "region":   np.tile(["North", "South", "East"], len(days)),
    "sales":    rng.gamma(shape=6, scale=180, size=len(days) * 3).round(2),
    "returns":  rng.integers(0, 12, size=len(days) * 3),
})

# --- Chained aggregation straight into a chart ---
totals = df.groupby("region")["sales"].sum().sort_values()
ax = totals.plot.barh(figsize=(8, 3), color="steelblue", title="Total Sales by Region")
ax.set_xlabel("Sales (GBP)")
ax.bar_label(ax.containers[0], fmt="%.0f", padding=3)    # value labels on bars
ax.spines[["top", "right"]].set_visible(False)           # remove chart junk
plt.tight_layout()
plt.savefig("by_region.png", dpi=150)
plt.close()

# --- Resample daily -> weekly, one line per region ---
weekly = (
    df.set_index("date")
      .groupby("region")["sales"]
      .resample("W")
      .sum()
      .unstack(level=0)          # regions become columns
)

ax = weekly.plot(figsize=(11, 4.5), linewidth=1.8, title="Weekly Sales by Region")
ax.set_ylabel("Sales (GBP)")
ax.legend(title="Region", frameon=False)
ax.grid(axis="y", alpha=0.3)
ax.spines[["top", "right"]].set_visible(False)
plt.tight_layout()
plt.savefig("weekly.png", dpi=150)
plt.close()

# --- Two charts sharing one figure, via ax= ---
fig, (left, right) = plt.subplots(1, 2, figsize=(12, 4))

df["sales"].plot.hist(bins=40, ax=left, color="darkseagreen", edgecolor="white")
left.set_title("Distribution of Daily Sales")
left.set_xlabel("Sales (GBP)")

df.boxplot(column="sales", by="region", ax=right)
right.set_title("Spread by Region")
right.set_xlabel("")
fig.suptitle("")                 # boxplot's auto-title is usually unwanted

plt.tight_layout()
plt.savefig("distribution.png", dpi=150)
plt.close()

print(weekly.tail(3).round(0))

The ax= argument is the bridge between the two libraries. Pandas draws the data; you keep the Matplotlib Axes and use its full API for labels, limits, gridlines, and annotations.


Common Mistakes

  1. Forgetting to set the index: df.plot() on a DataFrame with a default RangeIndex gives you an x-axis labelled 0, 1, 2. Call set_index("month") or pass x="month".
  2. Plotting non-numeric columns: a string column silently vanishes or raises. Select the numeric columns explicitly.
  3. Nothing appears in a script: outside a notebook you need plt.show() to open a window or plt.savefig() to write a file. Neither happens by itself.
  4. Never calling plt.close() in a loop: after 20 figures Matplotlib warns that you are leaking memory, and it is right.
  5. Expecting a pie chart to communicate: humans compare lengths well and angles badly. Nearly every pie chart is a worse bar chart.
  6. Overlapping tick labels: long category names collide. rot=45 plus plt.tight_layout() fixes almost all of it, or switch to barh.
  7. Ignoring the returned Axes: writing five lines of Matplotlib setup around a plot when ax = df.plot(...) already handed you the object.
  8. Plotting 500,000 rows as a line chart: the renderer will try, slowly, and the result is a solid block. Resample or aggregate first.

Best Practices

  • Aggregate, then plot: groupby().sum().plot() is both faster and clearer than plotting raw rows and hoping.
  • Always label the axes and add units: ylabel="Sales (GBP)". An unlabelled axis makes a chart decoration rather than information.
  • Capture the Axes: ax = df.plot(...) gives you the whole Matplotlib API for the polish step.
  • Set figsize deliberately: the default is small; (10, 5) is a better starting point for anything you will show someone.
  • Remove chart junk: hide the top and right spines, use light gridlines, and drop the legend when there is only one series.
  • Use bar_label when exact values matter — it beats making the reader estimate against gridlines.
  • Seed your random data: np.random.default_rng(42) makes an example reproducible for whoever reads it next.
  • Save with dpi=150 or higher: the default 100 looks blurry in slides and documents.
  • Reach for Seaborn when the chart is statistical, and for Plotly when it needs to be interactive. Pandas plotting is for speed of exploration.

Practice Exercises

  1. The Quick Look: Load any CSV you have with pd.read_csv, set a sensible index, and produce a line chart, a histogram, and a horizontal bar chart of a grouped total — each in a single chained line.
  2. The Polished Chart: Take the bar chart from exercise 1 and add a title, axis labels with units, value labels on the bars, hidden top and right spines, and a saved PNG at dpi=200. Compare it side by side with the unpolished version.
  3. The Resample: Build a DataFrame of 365 days of random daily values with a DatetimeIndex, then plot the daily series and a monthly mean on the same axes using ax=. Explain in a comment why the monthly line is easier to read.