Skip to content

Commit

Permalink
Check cmap type before comparing to categories (#1462)
Browse files Browse the repository at this point in the history
  • Loading branch information
Azaya89 authored Dec 11, 2024
1 parent de6596a commit c2f9d2b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
11 changes: 9 additions & 2 deletions hvplot/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
process_derived_datetime_pandas,
_convert_col_names_to_str,
import_datashader,
is_mpl_cmap,
)
from .utilities import hvplot_extension

Expand Down Expand Up @@ -1420,7 +1421,7 @@ def _process_style(self, kwds, plot_opts):
valid_opts = []

cmap_opts = ('cmap', 'colormap', 'color_key')
categories = [
categorical_cmaps = [
'accent',
'category',
'dark',
Expand Down Expand Up @@ -1485,7 +1486,13 @@ def _process_style(self, kwds, plot_opts):
if 'color' in style_opts:
color = style_opts['color']
elif not isinstance(cmap, dict):
if cmap and any(c in cmap for c in categories):
# Checks if any of the categorical cmaps matches cmap;
# uses any() instead of `cmap in categorical_cmaps` to handle reversed colormaps (suffixed with `_r`).
# If cmap is LinearSegmentedColormap, get the name attr, else return the str typed cmap.
if (isinstance(cmap, str) or is_mpl_cmap(cmap)) and any(
categorical_cmap in getattr(cmap, 'name', cmap)
for categorical_cmap in categorical_cmaps
):
color = process_cmap(cmap or self._default_cmaps['categorical'], categorical=True)
else:
color = cmap
Expand Down
11 changes: 11 additions & 0 deletions hvplot/tests/testcharts.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,3 +606,14 @@ def test_table_datetime_index_displayed(self):

def test_table_multi_index_displayed(self):
raise SkipTest('Dask does not support MultiIndex Dataframes.')


def test_cmap_LinearSegmentedColormap():
# test for https://github.com/holoviz/hvplot/pull/1461
xr = pytest.importorskip('xarray')
mpl = pytest.importorskip('matplotlib')
import hvplot.xarray # noqa

data = np.arange(25).reshape(5, 5)
xr_da = xr.DataArray(data)
xr_da.hvplot.image(cmap=mpl.colormaps['viridis'])
9 changes: 9 additions & 0 deletions hvplot/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,3 +750,12 @@ def relabel_redim(hv_obj, relabel_kwargs, redim_kwargs):
if redim_kwargs:
hv_obj = hv_obj.redim(**redim_kwargs)
return hv_obj


def is_mpl_cmap(obj):
"""Check if the object is a Matplotlib LinearSegmentedColormap."""
if 'matplotlib' not in sys.modules:
return False
from matplotlib.colors import LinearSegmentedColormap

return isinstance(obj, LinearSegmentedColormap)

0 comments on commit c2f9d2b

Please sign in to comment.