pythonpandasjupyterbokehhvplot

How to remove empty categories in Bokeh when using hvplot?


I have a plot that has categories and subcategories. I want to plot it such that it is not stacked, but I want categories to not show up when their value is not present.

Below you can find sample code and a picture of what I am trying to do. On the picture you can see the place of B in X and C in Y. I want those to not be there. How do I do that?

import pandas as pd
import hvplot.pandas

df = pd.DataFrame({
    'category': ['A', 'A', 'B', 'B', 'C', 'C'],
    'subcategory': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
    'value': [10, 20, 0, 30, 40, 0]
})

df_filtered = df[df['value'] != 0]

grouped = df_filtered.groupby(['category', 'subcategory']).sum()

grouped.hvplot.bar(stacked=False, by='category')

incorrect plot


Solution

  • Unfortunately I didn't find the exact answer to your question but, here is a workaround:

    
        import seaborn as sns
        import matplotlib.pyplot as plt
        g = sns.catplot(kind='bar', data=df_filtered, col='subcategory', x='category', y='value',
                    hue='category', palette='rocket', dodge=False, sharex=False)
        plt.tight_layout()
        plt.show()
    
    

    the result would looks like this:

    enter image description here