bhylu.com

Advertisements

Pandas Bar Plots

Pandas plotting delegates to a plotting backend such as Matplotlib. A useful chart labels its values and reflects the actual grain of the grouped report.

How it works

This local-only example uses Matplotlib 3.11.2 with the non-interactive Agg backend and an empty output folder. It saves a 960-by-540 PNG from original fictional drop-offs. The browser Pandas runner is text-only and does not claim to provide that plotting environment or a file on your PC. The chart should accompany the source totals, not hide the small scope of the fixture.

Run the code

Run this figure locally with Matplotlib 3.11.2. Use an empty exercises folder; the script refuses to overwrite its output. The text-only browser runner does not provide this plotting environment.

For local work, use a separate virtual environment and run python bar-plot.py. Download the complete source. The reviewed local environment uses Python 3.12.14, Pandas 3.0.6 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with Pandas 2.2.3 and NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.

Example

bar-plot.py

import pandas as pd
import numpy as np

df = pd.DataFrame({
    "drop_id": [101, 102, 103, 104],
    "point": ["north", "south", "north", "south"],
    "material": ["leaves", "food", "food", "leaves"],
    "kg": [12., 8., 6., 10.],
    "bags": pd.array([3, 2, 1, 2], dtype="Int64"),
    "day": ["2026-10-01", "2026-10-01", "2026-10-02", "2026-10-02"],
})

from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
target = Path("point-totals.png")
if target.exists():
    raise FileExistsError("Choose an empty exercises folder")
totals = df.groupby("point", observed=True)["kg"].sum().sort_index()
fig, ax = plt.subplots(figsize=(8, 4.5), dpi=120)
totals.plot.bar(ax=ax, color="#0078d4", rot=0)
ax.set(xlabel="Collection point", ylabel="Recorded mass (kg)", title="Fictional compost drop-offs: recorded totals")
fig.tight_layout()
fig.savefig(target)
plt.close(fig)
print("Saved point-totals.png")

Expected result

Saved point-totals.png

Both points have eighteen kilograms in the supplied observations. The labels state recorded totals rather than implying complete real-world collection coverage. Review the saved image for readable axes and a truthful scale as well as checking that the file exists.

Total fictional compost mass by collection point: north 18 kilograms and south 18 kilograms.
Rendered locally from this lesson’s complete script. Fictional teaching data.

Use Pandas’s official reference for precise contracts, supported versions and numerical limitations.