diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 3d493c92026e..52b1094528fb 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -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. @@ -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 diff --git a/lib/matplotlib/axes/_axes.pyi b/lib/matplotlib/axes/_axes.pyi index 4be2c5536105..0c1aff77151e 100644 --- a/lib/matplotlib/axes/_axes.pyi +++ b/lib/matplotlib/axes/_axes.pyi @@ -583,6 +583,7 @@ class Axes(_AxesBase): weights: ArrayLike | None = ..., cmin: float | None = ..., cmax: float | None = ..., + adapt_lim: bool | str = ..., *, data=..., **kwargs diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 99af494c7880..fa89f6cb2579 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -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, @@ -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, )