Search code examples
pythonbar-chartbokehholoviewshvplot

Holoviews: Remove variables names from x axis on grouped bar chart


Quick question about a HoloViews grouped (unstacked) bar chart. How can I remove the x axis variable name ticks, but have them included in a legend?

Please see example below:

barchart without legend and superfluous xticks

I would like to do the following:

  1. For the red box, remove the names for the ticks "x" and "y"
  2. Add a legend for "x" and "y" aligned to their respective colours.

Code below:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import holoviews as hv
pd.options.plotting.backend = 'holoviews'

df1 = pd.DataFrame({
    'x': np.random.rand(10), 
    'y': np.random.rand(10),
})

my_plot = df1.plot(kind='bar')
my_plot

Thank you!


Solution

  • You can use .opts(multi_level=False) on your grouped barplot.
    This will remove your x-ticks for the secondary categorical variable and add a legend to your grouped barplot.

    However, you need HoloViews >=1.13 for this.
    This version is, as I write this, not available yet, but you can install it via:

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


    Code example:

    import numpy as np
    import pandas as pd
    import holoviews as hv
    pd.options.plotting.backend = 'holoviews'
    
    df1 = pd.DataFrame({
        'x': np.random.rand(10), 
        'y': np.random.rand(10),
    })
    
    my_grouped_barplot = df1.plot(kind='bar')
    
    # remove the 2nd categorical level with multi_level=False
    # this will remove your x-ticks and add a legend
    my_grouped_barplot.opts(multi_level=False)
    


    Resulting plot:

    grouped barchart with legend added and xticks removed