最新的散景分组条形图示例?

Up to date Bokeh grouped bar chart example?

我是 Bokeh 和 Pandas 的新手,我正在尝试根据一些查询结果生成分组条形图。

我的数据看起来像这样

Day         Fruit    Count
----------- -------- -------
2020-01-01  Apple    19
2020-01-01  Orange   8
2020-01-01  Banana   7
...
2020-02-23  Apple    15
2020-02-23  Orange   10
2020-02-23  Banana   12
2020-02-24  Apple    12
2020-02-24  Orange   17
2020-02-24  Banana   9

的答案中,这个数据布局似乎很容易处理。

我真的很难理解 grouped chart example 从最新的 API 发生了什么,以及如何将我的数据转换成格式中显示的格式例如。

我尝试在我的数据框中生成一个新列,其中有一天,使用转换的水果,但由于我不明白的错误而失败。我什至不知道这是不是正确的做法。

# add a grouped axis for group the bar chart
def grouped_axis (row ):
   return ( row['Day'], row['Fruit'] )

data_frame['day_fruit']=data_frame2.apply ( lambda row: grouped_axis(row), axis=1 )

谁能给我指出一个使用此类数据的示例?或者如果失败了,请解释我需要的代码让 Bokeh 将我的数据理解为分组条形图?

您正在寻找的是一种名为 pivot 的方法。

但在这种情况下您并不真正需要它 - 您链接的 Bokeh 示例已经处理了旋转数据,这就是为什么它必须将其按摩成可接受的形式。而对于您已经拥有的数据形状,您不需要做太多事情。

您可以在下面找到这两种方法的示例。请注意 mk_src_2 是多么简单。

import pandas as pd
from bokeh.io import show
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure

data = pd.DataFrame([['2020-01-01', 'Apple', 19],
                     ['2020-01-01', 'Orange', 8],
                     ['2020-01-01', 'Banana', 7],
                     ['2020-02-23', 'Apple', 15],
                     ['2020-02-23', 'Orange', 10],
                     ['2020-02-23', 'Banana', 12],
                     ['2020-02-24', 'Apple', 12],
                     ['2020-02-24', 'Orange', 17],
                     ['2020-02-24', 'Banana', 9]],
                    columns=['day', 'fruit', 'count'])


def mk_src_1(d):
    # Pivoting implicitly orders values.
    d = d.pivot(index='fruit', columns='day', values='count')
    x = [(fruit, day) for fruit in d.index for day in d.columns]
    counts = sum(d.itertuples(index=False), ())
    return ColumnDataSource(data=dict(x=x, counts=counts))


def mk_src_2(d):
    # Bokeh's FactorRange requires the X values to be ordered.
    d = d.sort_values(['fruit', 'day'])
    return ColumnDataSource(data=dict(x=list(zip(d['fruit'], d['day'])),
                                      counts=d['count']))


# source = mk_src_1(data)
source = mk_src_2(data)

p = figure(x_range=FactorRange(*source.data['x']), plot_height=250, title="Fruit Counts by Year",
           toolbar_location=None, tools="")

p.vbar(x='x', top='counts', width=0.9, source=source)

p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None

show(p)