Royalblue
Royalblue

Reputation: 701

Stacked bar chart using pandas DataFrame and vbar in Bokeh plot

I am looking for bokeh version (using vbar) of the following plot in matplotlib:

import pandas as pd
%matplotlib inline

data = [
    ['201720', 'cat1', 20],
    ['201720', 'cat2', 30],
    ['201720', 'cat3', 40],
    ['201721', 'cat1', 20],
    ['201721', 'cat2', 0],
    ['201721', 'cat3', 40],    
    ['201722', 'cat1', 50],
    ['201722', 'cat2', 60],
    ['201722', 'cat3', 10],    
]

df = pd.DataFrame(data, columns=['week', 'category', 'count'])

pt = df.pivot('week', 'category', 'count')

pt.plot(kind='bar', stacked=True)

enter image description here

I tried googling but I could not find a simple solution.

Upvotes: 0

Views: 3091

Answers (1)

Royalblue
Royalblue

Reputation: 701

I think the following code is the best I can do as of now:

from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
from bokeh.models.ranges import FactorRange
import pandas as pd

data = [
    ['201720', 'cat1', 20],
    ['201720', 'cat2', 30],
    ['201720', 'cat3', 40],
    ['201721', 'cat1', 20],
    ['201721', 'cat2', 0],
    ['201721', 'cat3', 40],
    ['201722', 'cat1', 50],
    ['201722', 'cat2', 60],
    ['201722', 'cat3', 10],
]

df = pd.DataFrame(data, columns=['week', 'category', 'count'])

pt = df.pivot('week', 'category', 'count')

pt = pt.cumsum(axis=1)

output_file("lines.html", title='Dashboard')

p = figure(title="count",
           x_axis_label='week', y_axis_label='category',
           x_range = FactorRange(factors=list(pt.index)),
           plot_height=300, plot_width=500)

p.vbar(x=pt.index, bottom=0, top=pt.cat1, width=0.2, color='red', legend='cat1')
p.vbar(x=pt.index, bottom=pt.cat1, top=pt.cat2, width=0.2, color='blue', legend='cat2')
p.vbar(x=pt.index, bottom=pt.cat2, top=pt.cat3, width=0.2, color='green', legend='cat3')


show(p)

The resulting plot looks like:

enter image description here

Including vbar(), Bokeh plotting methods do not seem to support 'vectorized input' or maybe I am missing something. Is this really the simplest way?

Upvotes: 1

Related Questions