Skip to content

Add feature: adapt_limit argument #26381

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7075,7 +7075,7 @@ def stairs(self, values, edges=None, *,
@_preprocess_data(replace_names=["x", "y", "weights"])
@_docstring.dedent_interpd
def hist2d(self, x, y, bins=10, range=None, density=False, weights=None,
cmin=None, cmax=None, **kwargs):
cmin=None, cmax=None, adapt_lim=False, **kwargs):
"""
Make a 2D histogram plot.

Expand Down Expand Up @@ -7173,9 +7173,30 @@ def hist2d(self, x, y, bins=10, range=None, density=False, weights=None,
if cmax is not None:
h[h > cmax] = None

x_min, x_max = xedges[0], xedges[-1]
y_min, y_max = yedges[0], yedges[-1]
if adapt_lim is True or isinstance(adapt_lim, str):
mask = ~np.isnan(h)
mask_flat_x = np.any(mask, axis=1)
mask_flat_y = np.any(mask, axis=0)

if adapt_lim is True or adapt_lim.lower() == 'x':
x_min = xedges[:-1][mask_flat_x].min()
x_max = xedges[1:][mask_flat_x].max()
x_pad = 0.01 * (x_max - x_min)
x_min -= x_pad
x_max += x_pad

if adapt_lim is True or adapt_lim.lower() == 'y':
y_min = yedges[:-1][mask_flat_y].min()
y_max = yedges[1:][mask_flat_y].max()
y_pad = 0.01 * (y_max - y_min)
y_min -= y_pad
y_max += y_pad

pc = self.pcolormesh(xedges, yedges, h.T, **kwargs)
self.set_xlim(xedges[0], xedges[-1])
self.set_ylim(yedges[0], yedges[-1])
self.set_xlim(x_min, x_max)
self.set_ylim(y_min, y_max)

return h, xedges, yedges, pc

Expand Down
1 change: 1 addition & 0 deletions lib/matplotlib/axes/_axes.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@ class Axes(_AxesBase):
weights: ArrayLike | None = ...,
cmin: float | None = ...,
cmax: float | None = ...,
adapt_lim: bool | str = ...,
*,
data=...,
**kwargs
Expand Down
2 changes: 2 additions & 0 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3180,6 +3180,7 @@ def hist2d(
weights: ArrayLike | None = None,
cmin: float | None = None,
cmax: float | None = None,
adapt_lim: bool | str = False,
*,
data=None,
**kwargs,
Expand All @@ -3193,6 +3194,7 @@ def hist2d(
weights=weights,
cmin=cmin,
cmax=cmax,
adapt_lim=adapt_lim,
**({"data": data} if data is not None else {}),
**kwargs,
)
Expand Down