Skip to content

Commit c2f9d2b

Browse files
authored
Check cmap type before comparing to categories (#1462)
1 parent de6596a commit c2f9d2b

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

hvplot/converter.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@
7676
process_derived_datetime_pandas,
7777
_convert_col_names_to_str,
7878
import_datashader,
79+
is_mpl_cmap,
7980
)
8081
from .utilities import hvplot_extension
8182

@@ -1420,7 +1421,7 @@ def _process_style(self, kwds, plot_opts):
14201421
valid_opts = []
14211422

14221423
cmap_opts = ('cmap', 'colormap', 'color_key')
1423-
categories = [
1424+
categorical_cmaps = [
14241425
'accent',
14251426
'category',
14261427
'dark',
@@ -1485,7 +1486,13 @@ def _process_style(self, kwds, plot_opts):
14851486
if 'color' in style_opts:
14861487
color = style_opts['color']
14871488
elif not isinstance(cmap, dict):
1488-
if cmap and any(c in cmap for c in categories):
1489+
# Checks if any of the categorical cmaps matches cmap;
1490+
# uses any() instead of `cmap in categorical_cmaps` to handle reversed colormaps (suffixed with `_r`).
1491+
# If cmap is LinearSegmentedColormap, get the name attr, else return the str typed cmap.
1492+
if (isinstance(cmap, str) or is_mpl_cmap(cmap)) and any(
1493+
categorical_cmap in getattr(cmap, 'name', cmap)
1494+
for categorical_cmap in categorical_cmaps
1495+
):
14891496
color = process_cmap(cmap or self._default_cmaps['categorical'], categorical=True)
14901497
else:
14911498
color = cmap

hvplot/tests/testcharts.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,3 +606,14 @@ def test_table_datetime_index_displayed(self):
606606

607607
def test_table_multi_index_displayed(self):
608608
raise SkipTest('Dask does not support MultiIndex Dataframes.')
609+
610+
611+
def test_cmap_LinearSegmentedColormap():
612+
# test for https://github.com/holoviz/hvplot/pull/1461
613+
xr = pytest.importorskip('xarray')
614+
mpl = pytest.importorskip('matplotlib')
615+
import hvplot.xarray # noqa
616+
617+
data = np.arange(25).reshape(5, 5)
618+
xr_da = xr.DataArray(data)
619+
xr_da.hvplot.image(cmap=mpl.colormaps['viridis'])

hvplot/util.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,3 +750,12 @@ def relabel_redim(hv_obj, relabel_kwargs, redim_kwargs):
750750
if redim_kwargs:
751751
hv_obj = hv_obj.redim(**redim_kwargs)
752752
return hv_obj
753+
754+
755+
def is_mpl_cmap(obj):
756+
"""Check if the object is a Matplotlib LinearSegmentedColormap."""
757+
if 'matplotlib' not in sys.modules:
758+
return False
759+
from matplotlib.colors import LinearSegmentedColormap
760+
761+
return isinstance(obj, LinearSegmentedColormap)

0 commit comments

Comments
 (0)