散景堆积条形图

时间:2020-02-23 18:03:28

标签: python pandas jupyter bokeh

我想用熊猫和散景在Jupyter中绘制堆积的条形图。 我有3栏:['Feedstuff','Month','Price']。 我想在x轴上有价格,在y轴上有每个饲料的名称,并按月份堆积条形图。 我的数据如下:

data=[
['feed_wheat','Jan',138.24],
['feed_wheat','Dec',141.84],
['wheat_feed','Jan',106.45], ], 
columns=['Feedstuff','Month','Price']

我的绘图代码

output_notebook()

source = ColumnDataSource(T_M_11)
fs=source.data['Feedstuff'].tolist()
mt=source.data['Month'].tolist()
pr=source.data['Price'].tolist()
colors = ["#A5D6F3", "#B7D8EB", "#72A2D0","#252825","#505D66","#71A5D8","#2A5581","#202E26","#3D545F",
         "#20364C","#6E9CD5","#3F64B4"]
data = {
    'Feedstuff' : fs,
     pr : mt
}


p = figure(x_range=fs, plot_height=250, title="Средняя цена за месяцы за 1 единицу корма (Ł/ton), в фунт стерлингов",
           toolbar_location=None,tools="hover", tooltips="$name @fs: @$name")

p.vbar_stack(mt, x='Feedstuff', width=0.9, color=colors,source=data,
             legend_label=mt)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xgrid.grid_line_color = None
p.axis.minor_tick_line_color = None
p.outline_line_color = None
p.legend.location = "top_left"
p.legend.orientation = "horizontal"

show(p)

这是错误的样子:

> BokehJS 1.4.0 successfully loaded.
>---------------------------------------------------------------------------
>TypeError                                 Traceback (most recent call last)
><ipython-input-361-b751cfb4a157> in <module>
>     9 data = {
>     10     'Feedstuff' : fs,
>---> 11      pr : mt
>     12 }
> 13 
>TypeError: unhashable type: 'list'

不幸的是,我的绘图代码无法正常工作。你能帮我吗?

1 个答案:

答案 0 :(得分:0)

使用您的数据DataFrame对我有用...

data_aux=pd.DataFrame(np.array(np.meshgrid(data['Feedstuff'].unique(), data['Month'].unique())).T.reshape(-1, 2), columns=['Feedstuff', 'Month']).merge(data, on=['Feedstuff',  'Month'], how='left').fillna(0)
data2 = {'Feedstuff' : data_aux['Feedstuff'].unique()}
data2.update(data_aux.groupby(['Month'])['Price'].apply(list).to_dict())

p= figure(y_range=fs, x_range=(0, 1000))

p.hbar_stack(mt, y='Feedstuff', height=0.9, color= ["#A5D6F3", "#B7D8EB"], source=ColumnDataSource(data2))
show(p)