Call ax.set_axis_off() to hide the axes frame, ticks, and labels, remove any existing legend with ax.get_legend().remove() (if created), eliminate internal subplot margins via fig.subplots_adjust(left=0, right=1, top=1, bottom=0) (or ax.margins(0)), and save with fig.savefig("output.png", bbox_inches="tight", pad_inches=0) to crop all surrounding whitespace so only the raw plot content remains.
Basic Example
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
fig, ax = plt.subplots(figsize=(5, 5))
ax.imshow(data, cmap="viridis", label="Heatmap")
# 1. Remove axes (spines, ticks, tick labels, axis titles, and background patch):
ax.set_axis_off()
# 2. Remove legend safely if one was attached by a plotting helper (e.g., Pandas/Seaborn):
legend = ax.get_legend()
if legend is not None:
legend.remove()
# 3. Eliminate data padding & figure margins, then export with zero outer white border:
ax.margins(0)
fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
fig.savefig("borderless_output.png", bbox_inches="tight", pad_inches=0, dpi=300)
plt.close(fig)
Key Details & Edge Cases
- Why
bbox_inches="tight"alone still leaves a ~0.1-inch white margin:- By default,
savefig(..., bbox_inches="tight")setspad_inches=0.1, preserving a narrow border around the cropped bounding box. Passingpad_inches=0alongsidebbox_inches="tight"removes that remaining padding completely.
- By default,
- Hidden empty
Textobjects can still inflatebbox_inches="tight":- Even after calling
ax.set_axis_off(), Matplotlib sometimes retains empty axis title or label text artists inside the tight bounding-box calculation, leaving a thin strip of whitespace on one edge. Callingfig.subplots_adjust(left=0, right=1, top=1, bottom=0)(orax.set_position([0, 0, 1, 1])) forces theAxesbox to span 100% of the figure canvas so even a standardfig.savefig("out.png")withoutbbox_inches="tight"has zero white border.
- Even after calling
- Removing legends added automatically by Pandas (
df.plot()) or Seaborn (sns.histplot()):- Pandas
.plot()creates a legend by default unless you passlegend=False, and Seaborn figure-level plots (FacetGrid) store their legend ong._legendrather thanax.get_legend(). Remove them cleanly withg._legend.remove()(for SeabornFacetGrid) orax.get_legend().remove()(for standardAxes).
- Pandas
- Transparent background instead of solid white (
transparent=True):- For non-rectangular plots (scatter plots, line charts, radar plots, or transparent overlays), add
transparent=Truetofig.savefig(..., bbox_inches="tight", pad_inches=0, transparent=True)so both the figure canvas and axes background render with alpha0instead of white pixels.
- For non-rectangular plots (scatter plots, line charts, radar plots, or transparent overlays), add
- Direct image export alternative (
plt.imsave) for pure 2D arrays:- If you are simply saving a NumPy image/heatmap array with a colormap and no vector overlays,
plt.imsave("raw.png", data, cmap="viridis")writes exact pixel-for-pixel dimensions directly without creating aFigure,Axes, or any border at all.
- If you are simply saving a NumPy image/heatmap array with a colormap and no vector overlays,
Comparison of Border, Axis, and Legend Removal Techniques in Matplotlib
| Technique | Removes Ticks, Spines & Labels? | Removes Outer Figure Whitespace? | Preserves Exact figsize * dpi Pixel Dimensions? |
Best Used When |
|---|---|---|---|---|
ax.set_axis_off() + savefig(..., bbox_inches="tight", pad_inches=0) (Recommended) |
Yes | Yes (crops tightly around visible artists) | No (output pixel size shrinks to tight content bounds) | Exporting borderless charts, maps, network graphs, or figure panels for papers/slides. |
ax.set_axis_off() + ax.set_position([0, 0, 1, 1]) + savefig("out.png") |
Yes | Yes (fills 100% of figure canvas) | Yes (exact figsize * dpi resolution) |
ML dataset generation or video frames requiring exact, uniform pixel dimensions. |
legend=False / ax.get_legend().remove() |
No (removes legend box only) | No | Yes | Suppressing auto-generated legends from Pandas .plot() or Seaborn plots while keeping axes. |
plt.imsave("out.png", array, cmap=...) |
Yes (bypasses Axes completely) |
Yes (1 data element = 1 pixel) | Yes (array.shape pixels) |
Saving raw 2D/3D NumPy arrays or colormapped heatmaps directly to PNG/JPG. |
You must log in or register to comment.
