Skip to content

Commit bcd80d5

Browse files
committed
refactor(color): simplify the continuous-fill block and align idioms (#700)
/simplify pass (behaviour-preserving): - continuous-reprocessing: drop the duplicated NaN-count warning across the try/except arms — coerce, then count once via pd.isna and warn once. - has_valid_color: build the distinct-colors set once instead of twice. - _add_legend_and_colorbar: branch on color_spec.is_categorical instead of duck-typing `source is not None and hasattr(remove_unused_categories)`. - to_rgba: use the module-level colors.to_rgba_array (matching _map_color_seg) instead of instantiating ColorConverter(); drop the now-unused import.
1 parent f79a1c8 commit bcd80d5

2 files changed

Lines changed: 13 additions & 21 deletions

File tree

src/spatialdata_plot/pl/_color.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
from matplotlib import colors, rcParams
1818
from matplotlib.cm import ScalarMappable
1919
from matplotlib.colors import (
20-
ColorConverter,
2120
Colormap,
2221
LinearSegmentedColormap,
2322
ListedColormap,
@@ -727,10 +726,10 @@ def to_rgba(self, cmap_params: CmapParams) -> np.ndarray:
727726
via norm+cmap with NaN/non-finite rows painted ``na_color``; an object vector mixes the two.
728727
"""
729728
if self.source_vector is not None: # categorical or none: color_vector holds per-row hex
730-
return np.asarray(ColorConverter().to_rgba_array(list(self.color_vector)))
729+
return np.asarray(colors.to_rgba_array(list(self.color_vector)))
731730
arr = np.asarray(self.color_vector)
732731
if arr.ndim == 2 and arr.shape[1] in (3, 4) and np.issubdtype(arr.dtype, np.number):
733-
return np.asarray(ColorConverter().to_rgba_array(arr))
732+
return np.asarray(colors.to_rgba_array(arr))
734733
rgba = np.empty((len(arr), 4), dtype=float)
735734
rgba[:] = colors.to_rgba(cmap_params.na_color.get_hex_with_alpha())
736735
if np.issubdtype(arr.dtype, np.number):
@@ -748,7 +747,7 @@ def to_rgba(self, cmap_params: CmapParams) -> np.ndarray:
748747
rgba[is_num] = cmap_params.cmap(norm(num[is_num]))
749748
color_mask = (~is_num) & series.notna().to_numpy()
750749
if color_mask.any():
751-
rgba[color_mask] = ColorConverter().to_rgba_array(series[color_mask].tolist())
750+
rgba[color_mask] = colors.to_rgba_array(series[color_mask].tolist())
752751
return rgba
753752

754753
def align_to_length(self, n: int, na_color: Color) -> ColorSpec:

src/spatialdata_plot/pl/render.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ def _add_legend_and_colorbar(
362362
if palette is None and fill_has_decorations:
363363
palette = color_spec.make_palette()
364364

365-
if color_source_vector is not None and hasattr(color_source_vector, "remove_unused_categories"):
365+
if color_spec.is_categorical:
366366
color_source_vector = color_source_vector.remove_unused_categories()
367367

368368
wants_colorbar = _should_request_colorbar(
@@ -690,31 +690,24 @@ def _render_shapes(
690690
if color_spec.is_continuous:
691691
cv = color_spec.color_vector
692692
_series = cv if isinstance(cv, pd.Series) else pd.Series(cv)
693-
694693
try:
695694
cv = np.asarray(_series, dtype=float)
696695
except (TypeError, ValueError):
697-
nan_count = int(_series.isna().sum())
698-
if nan_count:
699-
logger.warning(
700-
f"Found {nan_count} NaN values in color data. "
701-
"These observations will be colored with the 'na_color'."
702-
)
703696
cv = _series.to_numpy()
704-
else:
705-
if np.isnan(cv).any():
706-
nan_count = int(np.isnan(cv).sum())
707-
logger.warning(
708-
f"Found {nan_count} NaN values in color data. "
709-
"These observations will be colored with the 'na_color'."
710-
)
697+
nan_count = int(pd.isna(cv).sum())
698+
if nan_count:
699+
logger.warning(
700+
f"Found {nan_count} NaN values in color data. "
701+
"These observations will be colored with the 'na_color'."
702+
)
711703
color_spec = color_spec.evolve(color_vector=cv)
712704

713705
palette = color_spec.make_palette()
714706

707+
distinct_colors = set(color_spec.color_vector)
715708
has_valid_color = (
716-
len(set(color_spec.color_vector)) != 1
717-
or list(set(color_spec.color_vector))[0] != render_params.cmap_params.na_color.get_hex_with_alpha()
709+
len(distinct_colors) != 1
710+
or next(iter(distinct_colors)) != render_params.cmap_params.na_color.get_hex_with_alpha()
718711
)
719712
if has_valid_color and color_spec.is_categorical and col_for_color is not None:
720713
# necessary in case different shapes elements are annotated with one table

0 commit comments

Comments
 (0)