Search code examples
pythonbokehholoviewshvplotholoviz

Change the order of bars in a grouped barplot with hvplot/holoviews


I try to create a grouped bar plot but can't figure out how to influence the order of the barplot.

Given these example data:

import pandas as pd
import hvplot.pandas

df = pd.DataFrame({
    "lu": [200, 100, 10], 
    "le": [220, 80, 130], 
    "la": [60, 20, 15], 
    "group": [1, 2, 2],
})
df = df.groupby("group").sum()

I'd like to create a horizontal grouped bar plot showing the two groups 1 and 2 with all three columns. The columns should appear in the order of "le", "la" and "lu".

Naturally I'd try this with Hvplot:

df.hvplot.barh(x = "group", y = ["le", "la", "lu"])

With that I get the result below: grouped barplot in wrong order hvplot

Hvplot does not seem to care about the order I add the columns (calling df.hvplot.barh(x = "group", y = ["lu", "le", "la"]) doesn't change anything. Nor does Hvplot seem to care about the original order in the dataframe.

Are there any options to influence the order of the bars?


Solution

  • This has just been fixed in HoloViews 1.13.

    You can sort your barplot just like you wanted:

    df.hvplot.barh(x="group", y=["lu", "la", "le"])
    


    As I write this, HoloViews 1.13 is not officially available yet, but you can install it through:

    pip install git+https://github.com/holoviz/holoviews.git


    If you want even more control over the order, you can use .redim.values() on your grouped_barplot:

    group_specific_order = [2, 1]
    variable_specific_order = ['lu', 'la', 'le']
    
    # Note that group and Variable are the variable names of your dimensions here
    # when you use this on a different grouped barchart, then please change to the 
    # names of your own dimensions.
    your_grouped_barplot.redim.values(
        group=group_specific_order, 
        Variable=variable_specific_order,
    )