我正在尝试在bokeh中复制堆积的abd分组条形图以获取bokeh文档here: https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#stacked-and-grouped)中提供的分类数据我想在xaxis的“ day”和“ category”旁边获得两个分类级别。我尝试重现n系列的图表。
我收到了我不理解的错误消息。我的输入数据似乎与bokeh文档中的示例具有相同的格式,除了我要考虑包含值的n列(我在示例中给出了3个列,但我希望代码真正用于n列)。] >
是否可以堆叠两个以上的序列?为什么我的代码不起作用?有没有更有效的方法?
我的代码:
import pandas as pd import bokeh.io from bokeh.io import output_file, show from bokeh.models import ColumnDataSource, FactorRange from bokeh.plotting import figure data = [['Mon', '1' , 1.1 , 1.2 , 1.3 ], ['Mon', '2' , 2.1 , 2.2 , 2.3 ], ['Mon', '3' , 3.1 , 3.2 , 3.3 ], ['Tue', '1' , 4.1 , 4.2 , 4.3 ], ['Tue', '2' , 5.1, 5.2 , 5.3 ], ['Tue', '3' , 6.1 , 6.2 , 6.3 ]] df = pd.DataFrame(data, columns = ['day', 'category','col_1','col_2','col_3']) factors = list(df[['day','cat']].to_records(index=False)) factors_dict = {'x':factors} series = list(df.columns)[2:] series_dict = df.iloc[:,2:].to_dict('l') data_dict = {**factors_dict,**series_dict} source = ColumnDataSource(data_dict) p = figure(x_range=FactorRange(*factors), plot_height=250, toolbar_location=None, tools="") p.vbar_stack(series, x='x', width=0.9, alpha=0.5, color=["blue", "red", "green"], source=source, legend_label=series) p.y_range.start = 0 p.y_range.end = 18 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None p.legend.location = "top_center" p.legend.orientation = "horizontal" show(p)
ERROR
ValueError: expected an element of either Seq(String), Seq(Tuple(String, String)) or Seq(Tuple(String, String, String)), got [('Mon', '1'), ('Mon', '2'), ('Mon', '3'), ('Tue', '1'), ('Tue', '2'), ('Tue', '3')]
散景文档示例中的因素
[('Q1', 'jan'), ('Q1', 'feb'), ('Q1', 'mar'), ('Q2', 'apr'), ('Q2', 'may'), ('Q2', 'jun'), ('Q3', 'jul'), ('Q3', 'aug'), ('Q3', 'sep'), ('Q4', 'oct'), ('Q4', 'nov'), ('Q4', 'dec')]
我的代码中的因素
[('Mon', '1'), ('Mon', '2'), ('Mon', '3'), ('Tue', '1'), ('Tue', '2'), ('Tue', '3')]
我传递给x_range的因子具有与bokeh文档中提供的示例相同的形式,但是当我将它们传递给x_range时出现错误。
ColumnDataSource似乎也相同
{'x': [('Q1', 'jan'), ('Q1', 'feb'), ('Q1', 'mar'), ('Q2', 'apr'), ('Q2', 'may'), ('Q2', 'jun'), ('Q3', 'jul'), ('Q3', 'aug'), ('Q3', 'sep'), ('Q4', 'oct'), ('Q4', 'nov'), ('Q4', 'dec')], 'east': [5, 5, 6, 5, 5, 4, 5, 6, 7, 8, 6, 9], 'west': [5, 7, 9, 4, 5, 4, 7, 7, 7, 6, 6, 7]}
在我的示例中
{'x': [('Mon', '1'), ('Mon', '2'), ('Mon', '3'),
('Tue', '1'), ('Tue', '2'), ('Tue', '3')],
'col_1': [1.1, 2.1, 3.1, 4.1, 5.1, 6.1],
'col_2': [1.2, 2.2, 3.2, 4.2, 5.2, 6.2],
'col_3': [1.3, 2.3, 3.3, 4.3, 5.3, 6.3]}
我正在尝试在bokeh中为分类数据复制堆积的abd分组条形图,以在bokeh文档中显示以下类别数据:https://docs.bokeh.org/en/latest/docs/user_guide/categorical...。
这里的问题是您的factors
值不是2元组的字符串列表。由于您是根据DataFrame构造它的方式,因此它实际上是一个numpy记录的列表: