[Python] How to add labels to holoviz multi-index bar graphs?

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am working with multi-index bar charts. My implementation uses python/pandas/hvplot. For example, the example on the hvplot documentation works for my case - https://hvplot.holoviz.org/reference/tabular/bar.html

    But, I also need to add value labels on top of the bars. This is working with a simple bar graphs like so -

    import pandas as pd
    import hvplot.pandas # noqa
    from bokeh.sampledata.autompg import autompg_clean as autompg
    import hvplot
    import holoviews as hv

    autompg_long_form = autompg.groupby("yr").mean(numeric_only=True).reset_index()
    bar=autompg_long_form.hvplot.bar(x='yr', y="mpg", width=1000)
    labels = hv.Labels(data=autompg_long_form, kdims=['yr', 'mpg'], vdims='mpg')
    hvplot.show(bar*labels)


    However, expanding the approach, like this, to the multi-index case, is failing -

    # Multi-index bar plot with labels
    autompg_multi_index = autompg.query("yr<=80").groupby(['yr', 'origin']).mean(numeric_only=True)
    plot=autompg_multi_index.hvplot.bar(width=1000, rot=90)
    multi_labels = hv.Labels(data=autompg_multi_index, kdims=['origin', 'mpg'], vdims='mpg')
    hvplot.show(plot*multi_labels)


    The error is -

    raise ValueError(f"failed to validate {obj_repr}.{name}: {error}")
    ValueError: failed to validate FactorRange(id='p1003', ...).factors: expected an element of either Seq(String), Seq(Tuple(String, String)) or Seq(Tuple(String, String, String)), got [('70', 'Asia'), ('70', 'Europe'), ('70', 'North America'), ('71', 'Asia'), ('71', 'Europe'), ('71', 'North America'), ('72', 'Asia'), ('72', 'Europe'), ('72', 'North America'), ('73', 'Asia'), ('73', 'Europe'), ('73', 'North America'), ('74', 'Asia'), ('74', 'Europe'), ('74', 'North America'), ('75', 'Asia'), ('75', 'Europe'), ('75', 'North America'), ('76', 'Asia'), ('76', 'Europe'), ('76', 'North America'), ('77', 'Asia'), ('77', 'Europe'), ('77', 'North America'), ('78', 'Asia'), ('78', 'Europe'), ('78', 'North America'), ('79', 'Asia'), ('79', 'Europe'), ('79', 'North America'), ('80', 'Asia'), ('80', 'Europe'), ('80', 'North America'), np.str_('Asia'), np.str_('Europe'), np.str_('North America')]


    How do I remedy this issue to add labels to the multi-index bar chart? Has anyone done this before or knows how to do it?

    Thanks! in advance.

    PS: This post is a copy of the one I have asked on the holoviz forum with no luck.

    Continue reading...

Compartilhe esta Página