【问题标题】:How do the factors in factor_cmap in Bokeh work?Bokeh 中 factor_cmap 中的因子是如何工作的?
【发布时间】: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


    【解决方案1】:

    如果你的意思是你正在尝试这个:

    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 表示“基于值的 mfr 子因子的颜色映射”,但您仍然使用 圆柱体 作为因子配置颜色映射器地图:

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

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

    所以你可以这样做:

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

    根据 Spectral5 调色板中的制造商值比颜色多得多的事实,哪个“有效”:

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

    【讨论】:

    • 谢谢 - 我不敢相信我搞砸了一些愚蠢的事情,就像忘记索引从 0 开始一样,哇。对不起,如果这是一个愚蠢的问题,我很感激帮助。
    • 跟进:在嵌套类别部分下的文档上,为什么分组列示例的 start = 1 和 end = 2?这些因素不也是长度为 2 的吗?那么 end 参数不会超出索引范围吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2023-03-18
    • 1970-01-01
    • 2014-09-18
    • 2016-07-01
    相关资源
    最近更新 更多