python-3.x - Bokeh 中 factor_cmap 中的因子是如何工作的?
问题描述
我正在尝试从 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)
这会产生以下内容(同样,来自文档的屏幕截图): 分组 Vbar 输出
我想我理解 factor_cmap 在这里是如何工作的。数据帧的索引有多个因素,我们只通过切片来获取第一个(如 所示end = 1
)。但是,当我尝试根据第二个索引级别 , mfr
(setting start = 1 , end = 2
) 设置颜色时,索引映射中断,我得到 了这个。我基于我的假设进行此更改,即这些因素是分层的,我需要对它们进行切片以获得第二个级别。
我想我一定是在考虑用这些分类因素错误的索引,但我不确定我做错了什么。如何让分类映射器按因子的第二级着色?我假设因子的格式是 ('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
这意味着“基于mfr
值的子因素的颜色图”,但您仍在使用圆柱体配置颜色映射器作为地图的因素:factors=sorted(df.cyl.unique())
当颜色映射器在映射中查找一个值时
mfr="mazda"
,它没有找到任何东西(因为您只将柱面值放入映射中)因此它被着色为默认颜色灰色(如预期的那样)。
所以你可以做这样的事情:
index_cmap = factor_cmap('cyl_mfr',
palette=Spectral5,
factors=sorted(df.mfr.unique()),
start=1)
哪个“有效”以以下事实为模:制造商值比 Spectral5 调色板中的颜色多得多:
在实际情况下,您需要确保使用的调色板至少与您配置的(子)因子的数量一样大。
推荐阅读
- debugging - 尽管设置了 sourceLanguages,但 VSCode 中的 Rust 类型可视化不起作用
- javascript - 正则表达式 - JS 中的表单数据验证
- json - 获取json term的成员
- python - Pyspark 将列表列转换为嵌套结构列
- python - Altair:使用对数刻度的配色方案
- c# - C#如何用id替换文档
- java - Java在循环问题的对象数组中的2个字符串变量之间没有区别
- php - php 中的 Sizeof() 限制
- vuepress - 使用vuepress时链接公共文件夹下的html文件
- function - 具有日期时间差异的 JPA 查询