James MIller
James MIller

Reputation: 65

How to create grouped barplot from hv.Dataset?

I would like to create a grouped bar plot from a pandas.DataFrame using Holoviews Datasets.

In particular I would like to have bars grouped by their original column. Right now bars are being plotted on top of each other:

import pandas as pd
import holoviews as hv
hv.extension('bokeh')

df = pd.DataFrame({'A': list(range(10,15)),
                   'B' : list(reversed(range(20,25)))})
ds = hv.Dataset(df, kdims='index')
ds.to.bars(vdims='A')*ds.to.bars(vdims='B').opts(alpha=.5)

This results in: current snippet

However I would like to have them side-by-side, similar to the plot featured in the official docs (bottom of the page).

Upvotes: 3

Views: 1085

Answers (1)

philippjfr
philippjfr

Reputation: 4080

For plotting directly with pandas DataFrames I would recommend the hvPlot library which is built on top of HoloViews. HoloViews deals well with so called tidy data, while hvPlot is built to deal well with both tidy and wide data. Using hvPlot generating the plot you want is as simple as:

import hvplot.pandas
df.hvplot.bar()

bar plot

Using HoloViews directly you would have to use pd.melt to convert the data into a so called tidy format. That would look like this:

hv.Bars(pd.melt(df.reset_index(), ['index']), ['index', 'variable'], 'value')

melt_example

For a neat explanation for what pd.melt is doing see this visualization

Upvotes: 4

Related Questions