holoviz / holoviews

With Holoviews, your data visualizes itself.
https://holoviews.org
BSD 3-Clause "New" or "Revised" License
2.67k stars 399 forks source link

Util to create a custom legend #6320

Open ahuang11 opened 3 weeks ago

ahuang11 commented 3 weeks ago

Looking at https://examples.holoviz.org/gallery/ship_traffic/ship_traffic.html#interactive-plots I think it'd be helpful to include something like legend = hv.util.create_legend(groups, cmap); legend * plot or even simpler hv.util.add_legend(plot, groups, cmap)

import pandas as pd
import hvplot.pandas
import colorcet as cc
import holoviews as hv

groups = {
    "A": "apple",
    "B": "banana",
    "C": "cherry",
}
colors = cc.glasbey_bw_minc_20_minl_30
color_key = {
    list(groups.keys())[i]: tuple(int(e * 255.0) for e in v)
    for i, v in enumerate(colors[: (len(groups))][::-1])
}
legend = hv.NdOverlay(
    {
        groups[k]: hv.Points([0, 0], label=str(groups[k])).opts(
            color=cc.rgb_to_hex(*v), size=0
        )
        for k, v in color_key.items()
    }
)
legend.options(xaxis="bare", yaxis="bare", title="", toolbar=None)
jbednar commented 3 weeks ago

This issue is arguably a duplicate of https://github.com/holoviz/holoviews/issues/6203 , which itself is a duplicate of https://github.com/holoviz/holoviews/issues/6052, or at least there wouldn't be much need for such a utility if those issues were addressed. Plus there's some issue somewhere (couldn't quickly fiind it) that acknowledges that we now do create a legend automatically in many cases, it's just not usable, so we end up with two legends (the fake one as in the code above, plus an auto-generated one). The problem with the auto-generated one is that for ship_traffic, it would show the category number rather than the string name, and for census it would show 'w' instead of 'White'. So yes, a utility would be useful, but more useful in more cases would be to generate the key automatically, as long as we can accept a mapping dictionary from underlying category to displayed label. With that I don't think the user would often need a fully custom utility, though of course we could write one for our own purposes for use with datashade() and then also expose that to the few users who do want to control it manually.

ahuang11 commented 3 weeks ago

All these issues suggest this is a very useful feature to have.

The problem with the auto-generated one is that for ship_traffic, it would show the category number rather than the string name, and for census it would show 'w' instead of 'White'.

We can make it easier at least, like with hover_tooltips, it's easy to map variable names, so in this case, legend_labels opts.