pythonbokehholoviewshvplot

Holoviews - How to create side-by-side bars from dataframe columns?


I would like to create a Holoviews bar chart (using Bokeh backend) in which Year is on the X-axis and columns A and B on the Y-Axis. For each Year, I want bars for values from columns A and B to appear next to each other i.e. for Year 2008, I have bars of heights 1 and 3, for year 2009, I have bars 3 and 6 height, and so on. I have tried numerous different ways including the example of grouped bars in the documentation but can't get it to work. See example below:

%%opts Bars [xrotation=90 width=600 show_legend=False tools=['hover']]
df=pd.DataFrame({'Year':[2008,2009,2010,2011,2012,2013],
   'A': [1,2,3,4,5,6],'B':[3,6,9,12,15,18]})
print(df)
bars = hv.Bars(df, kdims=['Year'], vdims=['A'])
bars

Please help. I am losing my mind!


Solution

  • HoloViews generally works best when your data is in what's called a tidy format. However to make it easier to work with data like yours we have developed a companion library called hvPlot. To generate the plot you want you can simply run:

    import hvplot.pandas
    df=pd.DataFrame({'Year':[2008,2009,2010,2011,2012,2013],
       'A': [1,2,3,4,5,6],'B':[3,6,9,12,15,18]})
    df.hvplot.bar('Year')
    

    enter image description here

    Alternatively you can learn about the pd.melt method, which can take your data in a wide format and convert it to a tidy dataset:

    %%opts Bars [xrotation=90 width=600 show_legend=False tools=['hover']]
    df=pd.DataFrame({'Year':[2008,2009,2010,2011,2012,2013],
       'A': [1,2,3,4,5,6],'B':[3,6,9,12,15,18]})
    tidy_df = df.melt(id_vars=['Year'], value_vars=['A', 'B'])
    bars = hv.Bars(tidy_df, ['Year', 'variable'], ['value'])
    bars