Matplotlib charts: understand Figure and Axes, then save as PNG or PDF
In Matplotlib, a `Figure` contains the whole graphic, while an `Axes` is the region where data is plotted. Create both with `plt.subplots()`, then build the chart with Axes methods such as `ax.plot(...)` and `ax.set_title(...)`. This guide makes a fictional weekly-orders line chart, saves it as PNG, and then displays it. The official Matplotlib 3.11.2 documentation was checked on 2026-11-18.
Matplotlib charts: understand Figure and Axes, then save as PNG or PDF
In Matplotlib, a Figure contains the whole graphic, while an Axes is the region where data is plotted. Create both with plt.subplots(), then build the chart with Axes methods such as ax.plot(...) and ax.set_title(...). This guide makes a fictional weekly-orders line chart, saves it as PNG, and then displays it. The official Matplotlib 3.11.2 documentation was checked on 2026-11-18.
What is the difference between Figure, Axes and Axis?
A Figure is the complete graphic that can be shown in a window or saved to a file. It can contain several Axes; each Axes is a plotting region and the main place to set its title, axis labels and legend. An Axis is the x- or y-axis object that manages the scale, ticks and tick labels. The names are similar, but the Figure is the outer container, an Axes is one plot inside it, and an Axis is one scale belonging to that plot.
In a script, keep references such as fig, ax = plt.subplots(). Use ax to draw and customize the data, and fig to save the result. This explicit object-oriented style makes it easier to edit each plot independently or combine multiple Axes later. With the implicit pyplot style (plt.plot(...)), Matplotlib manages the current Figure and Axes for you. That is convenient for quick interactive work, but in reusable code with multiple plots it can be unclear which object a command will modify. The official guide recommends the explicit Axes interface for complex plots and reusable code.
Install Matplotlib and create a weekly chart
Install Matplotlib in the Python environment you will use:
python -m pip install -U matplotlibThe five weeks and order counts below are invented example values, not measurements from a real store or business. Save the script as weekly_orders.py and run it. It saves weekly_orders.png in the current working directory and opens a chart window when a GUI is available.
import matplotlib.pyplot as plt
weeks = ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5"]
orders = [120, 145, 138, 172, 190]
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.plot(weeks, orders, marker="o", label="Orders")
ax.set_title("Weekly orders (illustrative data)")
ax.set_xlabel("Week")
ax.set_ylabel("Orders (illustrative)")
ax.grid(axis="y", alpha=0.3)
ax.legend()
fig.savefig("weekly_orders.png", dpi=160, bbox_inches="tight")
plt.show()figsize sets the Figure size in inches. layout="constrained" adjusts Axes placement to help avoid overlap among the title, labels and tick marks. ax.plot receives week names for x and order counts for y; marker="o" marks each data point. The ax.set_* methods add a title and axis labels so a reader can understand the chart and its units on its own. The code sets a label and calls ax.legend() to display it.
The example saves with fig.savefig(...) before calling plt.show(). In a script, plt.show() is blocking by default: it waits for the chart window to close. After a blocking show, pyplot may close and unregister the Figure; a later pyplot save call can then save a new, empty Figure. If you need both a file and a window, save first, then call plt.show().
When should you choose PNG, PDF or SVG?
Matplotlib supports raster formats such as PNG and vector formats such as PDF and SVG. Raster images are made of pixels and are useful for screen previews or use alongside photos, but pixels may become visible when enlarged. Vector files describe lines and text mathematically, so they usually remain sharp when scaled for documents or print. Check that the target application and backend support your chosen format.
| Need | Example | Check |
|---|---|---|
| General screen image | fig.savefig("weekly_orders.png", dpi=160) | dpi affects raster pixel resolution |
| Vector image for a document | fig.savefig("weekly_orders.pdf") | Open it in a PDF viewer or document editor |
| Vector image for web/design | fig.savefig("weekly_orders.svg") | Check text and lines in an SVG-capable tool |
| Reduce excess whitespace | Add bbox_inches="tight" | Margins may change; inspect the saved result |
The file extension normally selects the format; to export the same chart another way, save as .pdf or .svg. dpi=160 controls resolution for raster output such as PNG. Vector output generally keeps lines and text sharp when enlarged, although DPI can affect rasterized elements included inside a vector file. bbox_inches="tight" can adjust whitespace around labels and the plot.
Verify the result and troubleshoot
Open weekly_orders.png in an image viewer or document and check that all five points, week names, order-count units and title are visible. If the file is missing, check the Python environment and current working directory first. A chart may still be saved even when the environment cannot open a GUI window. Matplotlib documents that headless environments can draw with the noninteractive Agg backend and save a file instead; plt.show() may not open a window there.
**`ModuleNotFoundError: No module named 'matplotlib'`:** run `python -m pip install -U matplotlib` using the same Python that runs the script. Check whether you installed it into a different interpreter or virtual environment.
**The saved file is empty or shows a new blank chart:** check whether `plt.show()` ran first and closed the Figure. Save before show and call `fig.savefig(...)` on the retained Figure reference.
**The title or axis labels are clipped:** create the Figure with `layout="constrained"` or add `bbox_inches="tight"` when saving. Open the result to confirm that clipping is resolved.
**No window appears:** check whether the environment has a GUI backend. On a server or in automation, save a file; to show a window, configure a GUI backend for that environment.
**The output format is unsupported:** check which formats the installed backend supports and match the file extension and `savefig` option.
The example order counts are fictional and do not indicate real business performance. With actual data, check the aggregation period and missing weeks, and match axis units and labels to the source-data definitions.
Sources
[Matplotlib documentation: Quick start](https://matplotlib.org/stable/users/explain/quick_start.html)
[Matplotlib documentation: Application interfaces](https://matplotlib.org/stable/users/explain/figure/api_interfaces.html)
[Matplotlib documentation: Introduction to Figures and saving](https://matplotlib.org/stable/users/explain/figure/figure_intro.html)
[Matplotlib API: Figure.savefig](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.savefig.html)
[Matplotlib API: pyplot.show](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.show.html)
[Matplotlib documentation: Installation](https://matplotlib.org/stable/install/index.html)