【问题标题】:Bar chart showing count of each category month-wise using Bokeh使用 Bokeh 显示每个类别的每月计数的条形图
【发布时间】:2017-12-20 16:09:01
【问题描述】:

我有如下数据:

因此,我需要明智地显示每个类别 year_month_id 中的计数。由于我有 12 个月,因此将有 12 个细分,并且在每个计数下 每个类中的 ID。 我正在寻找类似下图的内容。

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

【问题讨论】:

  • ID 列值在这里表示什么?如果您在这里发布一个示例,例如一年内应该为一个类别显示多少计数,那就太好了
  • 您想要一个沿着 x 轴的“类”条形图和沿着 y 轴的一些数量?我没有在您的数据中看到“计数”。你在别的地方有吗?
  • 您好@BenLove,添加了预期输出以供参考。Count 将是每个 year_month_id 下每个类中的 ID 计数。
  • 你能提供一个实际的 CSV 数据文本吗?表格图像对于构建工作示例没有用处。

标签: python bar-chart bokeh


【解决方案1】:

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

我是这样解决你的问题的:

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 变量的顶部,以便它可以更好地容纳数据,尽管我自己没有尝试过。

【讨论】:

  • 这很好用。不能感谢你。 @BenLove
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多