散景堆栈图图例不正确

时间:2019-03-27 13:56:48

标签: python bokeh stacked-chart

我有一个数据框

df = pd.DataFrame({'Category': ['<£5000', '£100K to £250K'],
               '01/01/2014': [8,1],
               '01/01/2015': [8,2],
               '01/01/2016': [7,1]})

我正在Bokeh中创建堆积图。创建图表很好,但是图例不正确。

grouped = df.groupby('Category')['01/01/2014', '01/01/2015', '01/01/2016'].mean().round(0)

source = ColumnDataSource(grouped)
countries = source.data['Category'].tolist()
p = figure(x_range=countries)

p.vbar_stack(stackers=['01/01/2014', '01/01/2015', '01/01/2016'],
         x='Category', source=source,
         legend = ['01/01/2014', '01/01/2015', '01/01/2016'],
         width=0.5, color=Spectral3)


p.title.text ='Average Number of Trades by Portfolio Size'
p.legend.location = 'top_right'

p.xaxis.axis_label = 'Portfolio Size'
p.xgrid.grid_line_color = None  #remove the x grid lines

p.yaxis.axis_label = 'Average Number of Trades'

show(p)

我认为在上面的一行中,我已经将传奇设定为年份。但是,如图所示,它已设置为图中的三个点。

legend = ['01/01/2014', '01/01/2015', '01/01/2016']

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您在图例列表中添加其他内容,它会显示正确的图例名称,只要它与ColumnDataSource中的日期不匹配即可。因此,解决问题的一种简单方法是在图例列表的每个日期后面添加一个空格。

import pandas as pd
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show
from bokeh.palettes import Spectral3

df = pd.DataFrame({'Category': ['<£5000', '£100K to £250K'],
               '01/01/2014': [8,1],
               '01/01/2015': [8,2],
               '01/01/2016': [7,1]})


grouped = df.groupby('Category')['01/01/2014', '01/01/2015', '01/01/2016'].mean().round(0)

source = ColumnDataSource(grouped)
countries = source.data['Category'].tolist()
p = figure(x_range=countries)

p.vbar_stack(stackers=['01/01/2014', '01/01/2015', '01/01/2016'],
         x='Category', source=source,
         legend = ['01/01/2014 ', '01/01/2015 ', '01/01/2016 '],
         width=0.5, color=Spectral3)


p.title.text ='Average Number of Trades by Portfolio Size'
p.legend.location = 'top_right'

p.xaxis.axis_label = 'Portfolio Size'
p.xgrid.grid_line_color = None  #remove the x grid lines

p.yaxis.axis_label = 'Average Number of Trades'

show(p)

enter image description here