How can DynamicMap conditionally display or hide element?

Hello!
I have a DynamicMap which should display a text annotation when the streamed input satisfies some conditions. Otherwise, the text should be hidden. I tried to return None in the DynamicMap callback, it gave

DynamicMap does not accept NoneType type, data elements have to be a ('ViewableElement', 'NdMapping', 'Layout').

How could I disable the dynamic map based on the callback?

Thank you!

Hi @wuyuanyi135

Try to provide a minimum, reproducible code example. It is the easiest to provide feedback on. Thanks.

Sorry I could not upload the notebook file. Here is the code to describe the question:

import holoviews as hv
hv.extension('bokeh')

curve = hv.Curve(range(0, 10))
tap = hv.streams.Tap(x=0, y=0, source=curve)
def conditional_line(x, y):
    if x >= 0 and x <= 5:
        return hv.VLine(x=x)
    else:
        return None  # What should return here to disable DynamicMap output?
dmap = hv.DynamicMap(conditional_line, streams=[tap])
curve * dmap

Desired behavior: mouse taps between x = 0 to x = 5, the vertical line should be drawn. Otherwise, no line should be drawn
Observed behavior: mouse taps between x=0-5, vline is drawn (OK); mouse taps at x>5, everything is cleared.

Hi @wuyuanyi135

I tried to play with your example. I get another error than the one you refer to above. I get

AssertionError: DynamicMap must only contain one type of object, not both NoneType and VLine.

So for your example I believe you need to return a VLine from the dynamic map always.

A Hack could be to return a VLine with some x outside the visible x-range.

import holoviews as hv
hv.extension('bokeh')

curve = hv.Curve(range(0, 10))
tap = hv.streams.Tap(x=0, y=0, source=curve)
def conditional_line(x, y):
    if x >= 0 and x <= 5:
        return hv.VLine(x=x)
    else:
        return hv.VLine(x=-100)
dmap = hv.DynamicMap(conditional_line, streams=[tap])
curve * dmap

Your use case of returning different types in the DynamicMap seems reasonable to me, so you could try to open a feature request on GitHub.

Thanks for providing the minimum code example. It’s the best way to get help and also help shape a code base of examples by and for the community. I’m also just a user and I learned something from your code example I can use in my work one day.

If this answer solves your problem please mark it as a solution.

And welcome to the community by the way :+1:

Thank you Marc,

I believe the original purpose of DynamicMap was similar to HoloMap so they meant to be compared consistently rather than displayed conditionally. I will consider this workaround.

Thank you

1 Like