首页 > 解决方案 > 从 DataFrame 在 Bokeh 中创建嵌套条形图

问题描述

我有一个现有的 DataFrame,它按职位和年份分组。我想以此在 Bokeh 中创建一个嵌套条形图,但我对要正确绘制它的内容感到困惑。

数据框:

                       size
fromJobtitle      year   

CEO               2000   236
                  2001   479
                  2002     4
Director          2000    42
                  2001   609
                  2002   188
Employee          1998    23
                  1999   365
                  2000  2393
                  2001  5806
                  2002   817
In House Lawyer   2000     5
                  2001    54
Manager           1999     8
                  2000   979
                  2001  2173
                  2002   141
Managing Director 1998     2
                  1999    14
                  2000   130
                  2001   199
                  2002    11
President         1999    31
                  2000   202
                  2001   558
                  2002   198
Trader            1999     5
                  2000   336
                  2001   494
                  2002    61
Unknown           1999   591
                  2000  2960
                  2001  3959
                  2002   673
Vice President    1999    49
                  2000  2040
                  2001  3836
                  2002   370

一个示例输出是:示例图

标签: pythonpandasdataframebar-chartbokeh

解决方案


我假设您有一个df包含三列fromJobtitle, year,的 DataFrame size。如果您有 MultiIndex,请重置索引。要使用 FactorRangefrom bokeh,我们需要一个带有两个字符串的元组列表(这很重要,浮点数不起作用),例如

[('CEO', '2000'), ('CEO', '2001'), ('CEO', '2002'), ...] 

依此类推。

这可以通过

df['x'] = df[['fromJobtitle', 'year']].apply(lambda x: (x[0],str(x[1])), axis=1)

这是所有重要的部分。其余bokeh的为你做。

from bokeh.plotting import show, figure, output_notebook
from bokeh.models import FactorRange
output_notebook()

p = figure(
    x_range=FactorRange(*list(df["x"])),
    width=1400
)
p.vbar(
    x="x",
    top="size",
    width=0.9,
    source=df,
)

show(p)

这是生成的图

条形图


推荐阅读