使用 Bokeh 显示每个类别按月计数的条形图

Bar chart showing count of each category month-wise using Bokeh

我有如下数据:

因此,据此,我需要明智地显示每个类别中的计数 year_month_id。因为我有 12 个月,所以会有 12 个细分,并且在每个计数下 每个 class 中的 ID。 像下图这样的东西就是我要找的东西。

现在 Bokeh 中的示例使用 ColumnDataSource 和字典映射,但我该如何为我的数据集执行此操作。
有人可以帮我吗? 以下是表格和图表格式的预期输出。

我相信 pandas Python 包会派上用场,用于准备绘图数据。它对于操作类似 table 的数据结构很有用。

我是这样处理你的问题的:

from pandas import DataFrame
from bokeh.io import show
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.palettes import Viridis5

# Your sample data
df = DataFrame({'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 1],
                'year_month_id': [201612, 201612, 201612, 201612, 201612, 201612, 201612, 201612, 201612, 201701],
                'class': ['A', 'D', 'B', 'other', 'other', 'other', 'A', 'other', 'A', 'B']
                })

# Get counts of groups of 'class' and fill in 'year_month_id' column
df2 = DataFrame({'count': df.groupby(["year_month_id", "class"]).size()}).reset_index()

df2 现在看起来像这样:

# Create new column to make plotting easier
df2['class-date'] = df2['class'] + "-" + df2['year_month_id'].map(str)

# x and y axes
class_date = df2['class-date'].tolist()
count = df2['count'].tolist()

# Bokeh's mapping of column names and data lists
source = ColumnDataSource(data=dict(class_date=class_date, count=count, color=Viridis5))

# Bokeh's convenience function for creating a Figure object
p = figure(x_range=class_date, y_range=(0, 5), plot_height=350, title="Counts",
           toolbar_location=None, tools="")

# Render and show the vbar plot
p.vbar(x='class_date', top='count', width=0.9, color='color', source=source)
show(p)

所以散景图看起来像这样:

当然你可以改变它以满足你的需要。我想到的第一件事是使 y_range 变量成为顶部,这样它可以更好地容纳数据,尽管我自己还没有尝试过。