Skip to content

Re-use histogram binning #247

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

Merged
merged 1 commit into from
Jan 15, 2024
Merged
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
24 changes: 14 additions & 10 deletions src/napari_matplotlib/histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@
_COLORS = {"r": "tab:red", "g": "tab:green", "b": "tab:blue"}


def _get_bins(data: npt.NDArray[Any]) -> npt.NDArray[Any]:
if data.dtype.kind in {"i", "u"}:
# Make sure integer data types have integer sized bins
step = np.ceil(np.ptp(data) / 100)
return np.arange(np.min(data), np.max(data) + step, step)
else:
# For other data types, just have 128 evenly spaced bins
return np.linspace(np.min(data), np.max(data), 100)


class HistogramWidget(SingleAxesWidget):
"""
Display a histogram of the currently selected layer.
Expand Down Expand Up @@ -70,13 +80,7 @@ def draw(self) -> None:

# Important to calculate bins after slicing 3D data, to avoid reading
# whole cube into memory.
if data.dtype.kind in {"i", "u"}:
# Make sure integer data types have integer sized bins
step = abs(np.max(data) - np.min(data)) // 100
step = max(1, step)
bins = np.arange(np.min(data), np.max(data) + step, step)
else:
bins = np.linspace(np.min(data), np.max(data), 100)
bins = _get_bins(data)

if layer.rgb:
# Histogram RGB channels independently
Expand Down Expand Up @@ -215,9 +219,9 @@ def draw(self) -> None:
if data is None:
return

_, bins, patches = self.axes.hist(
data, bins=50, edgecolor="white", linewidth=0.3
)
bins = _get_bins(data)

_, bins, patches = self.axes.hist(data, bins=bins.tolist())
patches = cast(BarContainer, patches)

# recolor the histogram plot
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src/napari_matplotlib/tests/baseline/test_histogram_2D.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src/napari_matplotlib/tests/baseline/test_histogram_3D.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.