Bokeh 中 factor_cmap 中的因子如何工作?

How do the factors in factor_cmap in Bokeh work?

我正在尝试根据 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 .

如果你是说你正在尝试这个:

index_cmap = factor_cmap('cyl_mfr', 
                         palette=Spectral5, 
                         factors=sorted(df.cyl.unique()), 
                         start=1, end=2)

那么至少有两个问题:

  • 2 超出了子因素列表 ('cyl', 'mfr') 的长度范围。您只需要 start=1 并保留 end 的默认值 None (这意味着到列表的末尾,与任何 Python 切片一样)。

  • 在这种特定情况下,start=1 表示 "colormap based on mfr sub-factors of the values",但您仍在使用 cylinders 配置颜色映射器作为地图的因素:

    factors=sorted(df.cyl.unique())
    

    当颜色映射器在映射中查找带有 mfr="mazda" 的值时,它没有找到任何东西(因为您只在映射中放置了柱面值)所以它被着色为默认颜色灰色(如预期)。

所以你可以这样做:

index_cmap = factor_cmap('cyl_mfr', 
                         palette=Spectral5, 
                         factors=sorted(df.mfr.unique()), 
                         start=1)

其中 "works" 取模制造商值比 Spectral5 调色板中的颜色多得多的事实:

在实际情况下,您需要确保使用的调色板至少与您配置的(子)因素的数量一样大。