Matplotlib draws data through a figure and axes, while its selected backend determines how the result is rendered.
Matplotlib figures: render a labeled report without a display server
Operation contract
The dispatch report uses the Agg backend before importing pyplot, then saves a labeled bar chart to an owned byte buffer. It closes the figure after saving. The PNG signature check confirms the returned container format; it does not evaluate whether the chart communicates its data honestly. Minor-unit labels prevent the displayed numbers from being mistaken for rupee amounts.
Failure and ownership boundary
This example uses fixture totals, no remote images and no browser screenshot. Rendering a chart does not repair incorrect aggregation. Repeated unclosed figures can retain memory even after an output buffer is discarded. Pandas groupby: retain missing keys and define all-null totals and Python ExitStack: unwind partially acquired resources provide the preceding and following boundaries.
Tested environment
Dependency check: this program was executed on CPython 3.14.6 with matplotlib==3.11.2. Install these versions in a separate virtual environment. The download includes the recorded environment snapshot; no third-party package is part of the website runtime.
Working program
from io import BytesIO
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
figure, axes = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
try:
axes.bar(["DEL", "BOM", "BLR"], [375, 250, 175], color="#286c83", width=0.6)
axes.set(title="Accepted receipts by region", ylabel="Amount (minor units)")
axes.set_ylim(bottom=0)
axes.spines[["top", "right"]].set_visible(False)
with BytesIO() as output:
figure.savefig(output, format="png", dpi=120)
image = output.getvalue()
print("PNG container:", image.startswith(b"\x89PNG\r\n\x1a\n"))
finally:
plt.close(figure)
print("open figures:", len(plt.get_fignums()))Output
PNG container: True
open figures: 0Costs and limits
Rendering work depends on artists, pixel dimensions and backend. Raster output retains pixel-related storage; increasing each dimension multiplies the pixel count. This fixture does not print compressed byte size because rendering details can change across package versions.
Common Mistakes
- Select a noninteractive backend before importing pyplot.
- A saved image does not automatically release its figure.
Connected lessons
Pandas groupby: retain missing keys and define all-null totals, Pandas chunked CSV aggregation: validate every chunk before returning totals, Python ExitStack: unwind partially acquired resources.
