Plot CSV amounts with Python and Matplotlib
Creates PNG and SVG bar charts from the first 100 finite numeric records, with no display server required.
Before you start
- Python 3.10 or later. Run in a working folder with a backup of your source; output files may be replaced unless opened in exclusive mode.
- Place input.csv in that folder. Examples use UTF-8, a comma delimiter and a header row. Column-specific recipes use id,label,amount,status,note; adapt names to your file.
python3 -m venv .venv
.venv/bin/python -m pip install matplotlib.venv/bin/python - <<'PY'
import csv
with open("input.csv", encoding="utf-8-sig", newline="") as source:
table = list(csv.reader(source, strict=True))
if not table:
raise ValueError("Expected a header row")
headers, rows = table[0], table[1:]
if any(len(row) != len(headers) for row in rows):
raise ValueError("Every record must match the header width")
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
id_column = headers.index("id")
amount_column = headers.index("amount")
points = []
for row in rows:
try:
value = float(row[amount_column])
if math.isfinite(value):
points.append((row[id_column], value))
except ValueError:
pass
points = points[:100]
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar([key for key, _ in points], [value for _, value in points])
ax.set(xlabel="id", ylabel="amount", title="First 100 numeric records")
fig.tight_layout()
fig.savefig("chart.png", dpi=150)
fig.savefig("chart.svg")
plt.close(fig)
print("Wrote chart.png and chart.svg")
PYLimits and output
- CSV has no stored type schema. Python keeps fields as strings until an example explicitly converts a value. These recipes do not add spreadsheet formula protection; import sensitive-looking strings as text in spreadsheets.
- This is an explicit first-100-record chart, not full-data aggregation. Floating-point plotting can round precise decimal amounts; skipped values are not plotted.
- This recipe retains the parsed table in memory; use a streaming approach for files that do not fit.
Documentation: Python CSV reader and writer; Matplotlib bar chart reference