Skip to content
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
48 changes: 28 additions & 20 deletions holoviews/plotting/bokeh/raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ def _create_row(attr):
else:
divider = ()


if first_selector is not None and data.attrs.get("selector") and self.selector_in_hovertool:
selector_row = (
Span(children=["Selector:"], style={"color": "#26aae1", "font-weight": "bold", "text_align": "right"}),
Expand Down Expand Up @@ -300,7 +299,33 @@ def get_data(self, element, ranges, style):
return (data, mapping, style)


class RGBPlot(ServerHoverMixin, LegendPlot):
class SyntheticLegendMixin(LegendPlot):

def _init_glyphs(self, plot, element, ranges, source):
super()._init_glyphs(plot, element, ranges, source)
if not ('holoviews.operation.datashader' in sys.modules and self.show_legend):
return
try:
cmap = self.lookup_options(element, 'style').options.get("cmap")
legend = categorical_legend(
element,
backend=self.backend,
# Only adding if it not None to not overwrite the default
**({"cmap": cmap} if cmap else {})
)
except Exception:
return
if legend is None:
return
legend_params = {k: v for k, v in self.param.values().items()
if k.startswith('legend')}
self._legend_plot = PointPlot(legend, keys=[], overlaid=1, **legend_params)
self._legend_plot.initialize_plot(plot=plot)
self._legend_plot.handles['glyph_renderer'].tags.append('hv_legend')
self.handles['synthetic_color_mapper'] = self._legend_plot.handles['color_color_mapper']


class RGBPlot(ServerHoverMixin, SyntheticLegendMixin):

padding = param.ClassSelector(default=0, class_=(int, float, tuple))

Expand All @@ -321,23 +346,6 @@ def _hover_opts(self, element):
return [(xdim.pprint_label, '$x'), (ydim.pprint_label, '$y'),
('RGBA', '@image')], {}

def _init_glyphs(self, plot, element, ranges, source):
super()._init_glyphs(plot, element, ranges, source)
if not ('holoviews.operation.datashader' in sys.modules and self.show_legend):
return
try:
legend = categorical_legend(element, backend=self.backend)
except Exception:
return
if legend is None:
return
legend_params = {k: v for k, v in self.param.values().items()
if k.startswith('legend')}
self._legend_plot = PointPlot(legend, keys=[], overlaid=1, **legend_params)
self._legend_plot.initialize_plot(plot=plot)
self._legend_plot.handles['glyph_renderer'].tags.append('hv_legend')
self.handles['rgb_color_mapper'] = self._legend_plot.handles['color_color_mapper']

def get_data(self, element, ranges, style):
mapping = dict(image='image', x='x', y='y', dw='dw', dh='dh')
if 'alpha' in style:
Expand Down Expand Up @@ -392,7 +400,7 @@ def get_data(self, element, ranges, style):
return (data, mapping, style)


class ImageStackPlot(RasterPlot):
class ImageStackPlot(RasterPlot, SyntheticLegendMixin):

_plot_methods = dict(single='image_stack')

Expand Down
41 changes: 31 additions & 10 deletions holoviews/plotting/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -968,8 +968,8 @@ def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
palette = None
if not isinstance(palette, list):
raise TypeError(f"cmap argument {cmap} expects a list, Cycle or valid {providers_checked} colormap or palette.")
if ncolors and len(palette) != ncolors:
return [palette[i%len(palette)] for i in range(ncolors)]
if ncolors and (n_palette := len(palette)) != ncolors:
return [palette[i%n_palette] for i in range(ncolors)]
return palette


Expand Down Expand Up @@ -1339,25 +1339,35 @@ def _process(self, element, key=None):
fire = [f'#{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}'
for r,g,b in fire_colors]

# Qualitative color maps, for use in colorizing categories
# Originally from Cynthia Brewer (http://colorbrewer2.org), via Bokeh
# Sets 1, 2, and 3 combined, minus indistinguishable colors
# Copied from datashader.colors
Sets1to3 = [
'#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628',
'#f781bf', '#999999', '#66c2a5', '#fc8d62', '#8da0cb', '#a6d854', '#ffd92f',
'#e5c494', '#ffffb3', '#fb8072', '#fdb462', '#fccde5', '#d9d9d9', '#ccebc5',
'#ffed6f',
]

class categorical_legend(Operation):
"""Generates a Points element which contains information for generating
a legend by inspecting the pipeline of a datashaded RGB element.

"""

backend = param.String()
backend = param.String(doc="Backend to use for rendering the categorical legend.")

cmap = param.Parameter(default=Sets1to3, allow_None=False, doc="""
Colormap used to color the categories in the legend.
""")

def _process(self, element, key=None):
import datashader as ds

from ..operation.datashader import datashade, rasterize, shade
rasterize_op = element.pipeline.find(rasterize, skip_nonlinked=False)
if isinstance(rasterize_op, datashade):
shade_op = rasterize_op
else:
shade_op = element.pipeline.find(shade, skip_nonlinked=False)
if None in (shade_op, rasterize_op):
if rasterize_op is None:
return None
hvds = element.dataset
input_el = element.pipeline.operations[0](hvds)
Expand All @@ -1371,14 +1381,25 @@ def _process(self, element, key=None):
except TypeError:
# Issue #5619, cudf.core.index.StringIndex is not iterable.
cats = list(hvds.data.dtypes[column].categories.to_pandas())
except AttributeError:
cats = list(unique_iterator(hvds.data[column]))
if cats == ['__UNKNOWN_CATEGORIES__']:
cats = list(hvds.data[column].cat.as_known().categories)
else:
cats = list(hvds.dimension_values(column, expanded=False))
colors = shade_op.color_key or ds.colors.Sets1to3

if isinstance(rasterize_op, datashade):
shade_op = rasterize_op
else:
shade_op = element.pipeline.find(shade, skip_nonlinked=False)
if shade_op is None:
colors = process_cmap(self.p.cmap, ncolors=len(cats), categorical=True)
else:
colors = shade_op.color_key or self.p.cmap
color_data = [(0, 0, cat) for cat in cats]
if isinstance(colors, list):
cat_colors = {cat: colors[i] for i, cat in enumerate(cats)}
ncolors = len(colors)
cat_colors = {cat: colors[i % ncolors] for i, cat in enumerate(cats)}
else:
cat_colors = {cat: colors[cat] for cat in cats}
cmap = {}
Expand Down
38 changes: 37 additions & 1 deletion holoviews/tests/plotting/bokeh/test_rasterplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pytest
from bokeh.models import CustomJSHover, HoverTool

from holoviews.element import RGB, Image, ImageStack, Raster
from holoviews.element import RGB, Image, ImageStack, Points, Raster
from holoviews.plotting.bokeh.raster import ImageStackPlot
from holoviews.plotting.bokeh.util import BOKEH_GE_3_4_0

Expand Down Expand Up @@ -473,3 +473,39 @@ def setUp(self):
self.ysize = 3
self.xsize = 4
super().setUp()


class TestSyntheticLegendPlot(TestBokehPlot):
__test__ = True

def setUp(self):
super().setUp()
ds = pytest.importorskip("datashader")

from holoviews.operation.datashader import datashade, rasterize
points = Points([(0, 0, 'A'), (1, 1, 'B'), (2, 2, 'C')], vdims=['Label'])
kwargs = dict(aggregator=ds.by('Label'), dynamic=False, width=10, height=10)
self.img_stack = rasterize(points, **kwargs).opts(show_legend=True)
self.rgb = datashade(points, **kwargs).opts(show_legend=True)

def test_image_stack_legend(self):
plot = bokeh_renderer.get_plot(self.img_stack)
mapper = plot.handles['synthetic_color_mapper']
assert mapper.factors == ['A', 'B', 'C']
glyph = plot._legend_plot.handles['glyph']
assert glyph.fill_color.field == 'color'
assert glyph.fill_color.transform is mapper

def test_image_stack_legend_with_cmap(self):
self.img_stack.opts(cmap=["red"])
plot = bokeh_renderer.get_plot(self.img_stack)
mapper = plot.handles['synthetic_color_mapper']
assert mapper.palette == ["red", "red", "red"]

def test_rgb_legend(self):
plot = bokeh_renderer.get_plot(self.rgb)
mapper = plot.handles['synthetic_color_mapper']
assert mapper.factors == ['A', 'B', 'C']
glyph = plot._legend_plot.handles['glyph']
assert glyph.fill_color.field == 'color'
assert glyph.fill_color.transform is mapper
Loading