Bokeh中factor_cmap对vbar生效但scatter不生效问题
解决Bokeh中Scatter图层factor_cmap颜色映射失效问题
你的问题是:在Bokeh中叠加Scatter图层时,使用factor_cmap做分类颜色映射,所有散点颜色一致,而VBar图层的颜色映射正常。
问题原因
当x轴为分类变量(FactorRange)时,Scatter图层对factor_cmap的解析逻辑与VBar略有差异,直接传入factor_cmap作为fill_color可能无法正确关联分类字段。
解决方案:提前计算颜色列并绑定到数据源
最可靠的解决方法是预先计算每个分类对应的颜色,将其作为新字段加入ColumnDataSource,然后在Scatter图层中直接引用该颜色字段。
修正后的完整代码:
import pandas as pd from bokeh.plotting import figure, output_notebook, show from bokeh.models import ColumnDataSource from bokeh.transform import factor_cmap from bokeh import palettes my_fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] my_counts = [5, 3, 4, 2, 4, 6] # 预先计算每个水果对应的颜色 palette = palettes.Spectral6 fruit_color = {fruit: palette[i] for i, fruit in enumerate(my_fruits)} colors = [fruit_color[fruit] for fruit in my_fruits] source = ColumnDataSource(data=dict(my_fruits=my_fruits, my_counts=my_counts, colors=colors)) p = figure(x_range=my_fruits, plot_height=250, toolbar_location=None, title="Fruit Counts") # VBar图层保持原写法 p.vbar(x='my_fruits', top='my_counts', width=0.9, source=source, line_color='white', fill_color=factor_cmap('my_fruits', palette=palette, factors=my_fruits)) # Scatter图层直接引用预先计算的colors字段 p.scatter('my_fruits', 'my_counts', source=source, size=50, fill_color='colors', marker="dot", legend_field='my_fruits') p.xgrid.grid_line_color = None p.y_range.start = 0 p.y_range.end = 9 p.legend.orientation = "horizontal" p.legend.location = "top_center" show(p)
另一种简化方案:明确指定颜色映射逻辑
如果你不想预先计算颜色列,也可以通过调整factor_cmap的使用方式,确保Scatter图层正确解析分类映射:
# 替换原Scatter图层代码 p.scatter('my_fruits', 'my_counts', source=source, size=50, fill_color=factor_cmap('my_fruits', palette=palettes.Spectral6, factors=my_fruits), marker="dot", legend_field='my_fruits')
注:该方法在部分Bokeh版本中可能存在兼容性问题,优先推荐预先计算颜色列的方案。
内容的提问来源于stack exchange,提问作者Trevor
相关产品推荐
相关产品推荐

