python - 从 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
解决方案
我假设您有一个df
包含三列fromJobtitle
, year
,的 DataFrame size
。如果您有 MultiIndex,请重置索引。要使用
FactorRange
from 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)
这是生成的图
推荐阅读
- java - 如何在不创建新对象类的情况下返回对象类?
- node.js - 如何分发使用电子构建器构建的构建可执行文件
- c# - 定义和反序列化空类
- c++ - Eclipse/CDT_C++ 给出“语义错误_”类型 XXX 无法解析”。项目运行
- html - HTML单选按钮CSS样式:删除默认灰色圆圈
- java - Java Akka Actor 和流
- java - 创建地图
> 使用 Stream API 对列表元素进行排序的位置 - python - 在绘图中使用滑块时如何更改轴标题
- symfony - symfony fetchall 与 manyToOne 关系多次返回相同的对象
- ruby-on-rails - 从 rake 任务中添加 Ruby on Rails ActiveJob 后台任务