堆积条形图使用熊猫DataFrame和散景图中的vbar

时间:2017-07-02 06:41:12

标签: matplotlib dataframe bokeh

我正在寻找matplotlib中以下情节的散景版(使用vbar):

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

我试过谷歌搜索,但我找不到一个简单的解决方案。

1 个答案:

答案 0 :(得分:1)

我认为以下代码是我现在能做的最好的代码:

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)

结果情节如下:

enter image description here

包括vbar(),Bokeh绘图方法似乎不支持'矢量化输入'或者我可能缺少某些东西。这真的是最简单的方法吗?