如何使用Python Bokeh的LinearColorMapper绘制圆形散点图
改用LinearColorMapper绘制鸢尾花散点图的实现方案
嘿,我来帮你把原来用字典映射颜色的鸢尾花散点图代码,改成用LinearColorMapper实现的版本~
首先得明确:LinearColorMapper是基于数值范围来映射颜色的,而我们的鸢尾花物种是分类变量,所以第一步要先把分类的物种名转换成对应的数值标签,之后就能用颜色映射器来关联数值和颜色了。
完整修改后的代码
from bokeh.plotting import figure, show, output_file from bokeh.sampledata.iris import flowers from bokeh.models import LinearColorMapper, ColorBar import pandas as pd # 1. 将分类的物种名转换为数值标签(0、1、2分别对应三个物种) flowers['species_num'] = pd.factorize(flowers['species'])[0] # 2. 定义LinearColorMapper:指定调色板、数值范围(low是最小数值,high是最大数值) # 这里用你原来的红、绿、蓝对应三个物种,也可以用Bokeh内置调色板比如Viridis256 palette = ['red', 'green', 'blue'] color_mapper = LinearColorMapper(palette=palette, low=flowers['species_num'].min(), high=flowers['species_num'].max()) # 3. 创建绘图对象 p = figure(title="Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' # 4. 绘制圆形散点:使用color参数绑定映射器,同时指定数据源 p.circle( x="petal_length", y="petal_width", source=flowers, # 传入数据源,让Bokeh识别字段 color={'field': 'species_num', 'transform': color_mapper}, # 用映射器关联数值和颜色 fill_alpha=0.2, size=10 ) # 可选:添加颜色条,展示数值与物种的对应关系 color_bar = ColorBar(color_mapper=color_mapper, label_standoff=12, title='Species', ticker=[0,1,2], formatter=lambda x: ['setosa', 'versicolor', 'virginica'][int(x)]) p.add_layout(color_bar, 'right') # 输出HTML文件 output_file("iris.html", title="iris.py example") show(p)
关键修改点说明
- 分类转数值:用
pd.factorize把三个物种名转换成0、1、2的数值,这样LinearColorMapper就能基于这个数值范围做颜色映射。 - 颜色映射器配置:指定调色板和数值的最小/最大值,确保每个数值对应到调色板里的颜色。
- 散点绘制的参数变化:不再手动生成颜色列表,而是通过
source传入数据集,用{'field': 'species_num', 'transform': color_mapper}来让Bokeh自动完成颜色映射。 - 可选的颜色条:添加
ColorBar可以让观看者清楚知道每个颜色对应的物种,提升图形可读性。
这样修改后,就能用LinearColorMapper替代原来的字典映射,实现同样的颜色区分效果,而且如果后续有更多分类或者需要渐变颜色,这种方式扩展性更强~
内容的提问来源于stack exchange,提问作者littleworth
相关产品推荐
相关产品推荐

