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

问题描述 投票:0回答:1

我正在尝试从Pandas数据框中构造散景中的分组垂直条形图。我正在努力理解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
1个回答
0
投票

如果您是要尝试此操作:

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

然后至少存在两个问题:

  • 2对于子因子('cyl', 'mfr')的长度超出范围。您只需要start=1并保留其end的默认值Nonw(这意味着到列表的末尾,对于任何Python slice来说都是正常的)。

  • start=1表示“基于mfr的颜色图),但您仍在提供cylinders作为要映射的因素:

    factors=sorted(df.cyl.unique())
    
© www.soinside.com 2019 - 2024. All rights reserved.