How do you remove axes, legends, and extra white borders from a Matplotlib figure? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you remove axes, legends, and extra white borders from a Matplotlib figure?

message-square
0

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") sets pad_inches=0.1, preserving a narrow border around the cropped bounding box. Passing pad_inches=0 alongside bbox_inches="tight" removes that remaining padding completely.
  • Hidden empty Text objects can still inflate bbox_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. Calling fig.subplots_adjust(left=0, right=1, top=1, bottom=0) (or ax.set_position([0, 0, 1, 1])) forces the Axes box to span 100% of the figure canvas so even a standard fig.savefig("out.png") without bbox_inches="tight" has zero white border.
  • Removing legends added automatically by Pandas (df.plot()) or Seaborn (sns.histplot()):
    • Pandas .plot() creates a legend by default unless you pass legend=False, and Seaborn figure-level plots (FacetGrid) store their legend on g._legend rather than ax.get_legend(). Remove them cleanly with g._legend.remove() (for Seaborn FacetGrid) or ax.get_legend().remove() (for standard Axes).
  • Transparent background instead of solid white (transparent=True):
    • For non-rectangular plots (scatter plots, line charts, radar plots, or transparent overlays), add transparent=True to fig.savefig(..., bbox_inches="tight", pad_inches=0, transparent=True) so both the figure canvas and axes background render with alpha 0 instead of white pixels.
  • 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 a Figure, Axes, or any border at all.

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.