1

I am trying to create a custom hover tool using which takes the y-value of the plot and maps the value to different value.

The code I could come up with so far to achieve this functionality is

from bokeh.models import HoverTool
import holoviews as hv

df = pd.DataFrame(
    {
        "zero": [0, 0, 0, 0, 0, 0, 0],
        "one": [1, 1, 1, 1, 1, 1, 1],
        "two": [2, 2, 2, 2, 2, 2, 2],

    }
)

mapping = {i: c for i, c in enumerate(df.columns)}


def col_mapping(num):
    return mapping[int(num)]


hover = HoverTool(tooltips=[("x", "$x"), ("y", "$y")])

img = hv.Image((df.index, np.arange(df.shape[1]), df.T)).opts(tools=[hover])
img

x and y will be float values. So the idea is to map the y coordinates to its corresponding value in the mapping dictionary

Let me know how I can get a new value in the hover tool so that when the value is b/w 0 and 1 it will be

Thanks

RTM
  • 759
  • 2
  • 9
  • 22
  • The `mapping` dictionary is nothing but `{0: 'zero', 1: 'one', 2: 'two'}`. How would you map floats with it? Suppose you somehow manage to do that - what do you want to with that newly mapped value? Display it on the tooltip or something else? – Eugene Pakhomov Apr 21 '20 at 07:18
  • `col_mapping` converts floats to int. Yes. The idea is to find a way to display it on the tooltip – RTM Apr 21 '20 at 07:42

1 Answers1

3

Here's how I'd do it:

code = f"return ({json.dumps(mapping)})[Math.floor(special_vars.y)];"
hover = HoverTool(tooltips=[("x", "$x"), ("y", "$y"), ('mapped_y', '$y{0}')],
                  formatters={'$y': CustomJSHover(code=code)})

If you need a some more complicated code than that of col_mapping, then you'd have to use a ColumnDataSource and just add to it the fully transformed column.

Eugene Pakhomov
  • 9,309
  • 3
  • 27
  • 53
  • Thanks a lot Eugene. That is exactly what I am looking for. I didn't know javascript to understand how to use CustomJSHover but your answered is precisely what I am looking for – RTM Apr 21 '20 at 14:51
  • Is it possible to explain why the third option is written as `('mapped_y', 'y{0}')` and how did the CustomerJSHover used only `mapped_y` and not `x` or `y`. Is it because of use of `special_vars` in the `code` function – RTM Apr 21 '20 at 14:56
  • 1
    The `{0}` is needed to trigger the formatter. In fact, you can write anything within those `{}` if you don't use it. The formatter is not used for `$x` because the `formatters` field has only `$y`, and it's not used for `$y` because it doesn't have the `{0}` part. – Eugene Pakhomov Apr 21 '20 at 15:29
  • Thanks a lot once again. That makes lot of sense – RTM Apr 21 '20 at 15:32
  • I'll leave this here for further reference: [bokeh-formatting-tooltip-fields](https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#formatting-tooltip-fields) – mths Jul 26 '22 at 14:00