【发布时间】:2020-06-04 20:46:02
【问题描述】:
我正在尝试根据 pandas 数据框在 Bokeh 中构建一个分组的垂直条形图。我正在努力理解 factor_cmap 的使用以及颜色映射如何与这个函数一起工作。文档 (https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#pandas) 中有一个示例有助于遵循,这里:
from bokeh.io import output_file, show
from bokeh.palettes import Spectral5
from bokeh.plotting import figure
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.transform import factor_cmap
output_file("bar_pandas_groupby_nested.html")
df.cyl = df.cyl.astype(str)
df.yr = df.yr.astype(str)
group = df.groupby(by=['cyl', 'mfr'])
index_cmap = factor_cmap('cyl_mfr', palette=Spectral5, factors=sorted(df.cyl.unique()), end=1)
p = figure(plot_width=800, plot_height=300, title="Mean MPG by # Cylinders and Manufacturer",
x_range=group, toolbar_location=None, tooltips=[("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")])
p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=group,
line_color="white", fill_color=index_cmap, )
p.y_range.start = 0
p.x_range.range_padding = 0.05
p.xgrid.grid_line_color = None
p.xaxis.axis_label = "Manufacturer grouped by # Cylinders"
p.xaxis.major_label_orientation = 1.2
p.outline_line_color = None
show(p)
这会产生以下内容(同样,来自文档的屏幕截图): Grouped Vbar output
我想我了解 factor_cmap 在这里的工作原理。数据帧的索引有多个因素,我们只通过切片取第一个(如end = 1 所示)。但是,当我尝试根据第二个索引级别 mfr (设置 start = 1 , end = 2) 设置颜色时,索引映射中断,我得到 this。我基于我的假设进行了此更改,即这些因素是分层的,我需要对它们进行切片以获得第二个级别。
我想我一定是在考虑使用这些分类因素错误的索引,但我不确定我做错了什么。如何让分类映射器按因子的第二级着色?我假设因子的格式是 ('cyl', 'mfr') 但也许这个假设是错误的?
这里是 factor_cmap 的文档,虽然它不是很有帮助:https://docs.bokeh.org/en/latest/docs/reference/transform.html#bokeh.transform.factor_cmap。
【问题讨论】:
标签: python-3.x data-visualization bokeh