散景堆栈图图例不正确

Bokeh stack chart legend incorrect

我有一个数据框

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']

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

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)