Python Tutorial / Visualize Results with Matplotlib

Matplotlib builds charts with explicit data, axes and labels. Start with a comparison whose units are clear, and choose between showing a window and saving an image according to the execution environment.

Choose the comparison before the chart

A bar chart can compare category totals with categories on the horizontal axis and amounts on the vertical axis. A time trend needs ordered date data. A chart cannot repair an incorrect aggregation, so verify values, units and missing data first.

Install the package in the project environment:

python -m pip install matplotlib

This example uses English labels. Other scripts may require an installed font supporting their characters; check font availability and licensing before relying on a particular font.

For the relevant APIs and platform requirements, see Visualize Results with Matplotlib documentation.

Create and save the complete chart

Use a fresh output folder because saving replaces expense-chart.png if it exists.

Save the complete code below as chart.py in a separate practice folder, using UTF-8. Run python chart.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

categories = ["food", "transport"]
amounts = [11500, 2500]
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
bars = ax.bar(categories, amounts, color=["#2b6cb0", "#d69e2e"])
ax.set_ylabel("Amount (KRW)")
ax.set_title("Expenses by category")
ax.set_ylim(0, max(amounts) * 1.2)
ax.bar_label(bars, fmt="%.0f", padding=3)
fig.savefig("expense-chart.png", dpi=160)
plt.close(fig)
print("saved expense-chart.png")

Expected output:

saved expense-chart.png

Distinguish Figure, Axes and the backend

Figure is the whole image; Axes is the area containing coordinates and data. Explicit fig and ax references make it clear which chart an operation modifies when several figures exist.

Agg produces files without a graphical interface and is useful for automated reports. For a desktop window, remove the Agg selection and call plt.show() after saving; a GUI backend must be available. Close figures after repeated generation to release their resources.

Inspect the saved result

  1. Open expense-chart.png and verify two bars labeled 11500 and 2500.
  2. Check the KRW unit and the zero baseline.
  3. Reduce the figure width, inspect clipped or overlapping labels and then restore the original dimensions.

Use a new dated or run-specific output path when report versions must be retained. Do not use truncated axes or exaggerated visual area to make a small difference appear larger. The pandas aggregation lesson supplies validated category totals suitable for plotting.