You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

因ColumnDataSource兼容性问题引发运行时错误,求解决思路

解决ColumnDataSource运行时错误的思路

嘿,我看了你的代码片段,能发现两个直接导致运行时错误的问题,咱们一步步来搞定:

1. 先修复低级拼写错误

你在生成color列的时候,迭代对象写成了flowe...,明显是flowers的拼写不全,这会直接触发NameError——Python根本找不到名为flowe的对象。

错误代码片段:

flowers['color']=[colormap[x] for x in flowe...

修正后(建议明确指定取species列,避免后续数据结构变化出问题):

flowers['color']=[colormap[x] for x in flowers['species']]

2. 正确使用ColumnDataSource

如果你的报错和CDS直接相关,大概率是没把数据正确传入CDS,或者绘图时没正确引用CDS的列。下面是完整的修正代码,包含CDS的标准用法:

# Plotting flower species
# Importing libraries
from bokeh.plotting import figure
from bokeh.io import output_file, show
from bokeh.sampledata.iris import flowers
from bokeh.models import Range1d, PanTool, ResetTool, HoverTool, ColumnDataSource, LabelSet

colormap={'setosa':'red','versicolor':'green','virginica':'blue'}
# 修复拼写错误,明确关联species列
flowers['color']=[colormap[x] for x in flowers['species']]

# 将DataFrame转为ColumnDataSource(Bokeh推荐的数据源格式)
source = ColumnDataSource(flowers)

# 创建绘图对象,指定需要的工具
p = figure(tools=[PanTool(), ResetTool(), HoverTool()], title="Iris Flower Species")
# 绘图时必须引用CDS中的列名,不能直接用原始DataFrame的字段
p.circle(x='petal_length', y='petal_width', color='color', source=source, size=10)

# 如果要添加LabelSet,同样要绑定CDS
labels = LabelSet(x='petal_length', y='petal_width', text='species', source=source)
p.add_layout(labels)

# 输出并展示图表
output_file("iris_plot.html")
show(p)

额外排查方向

如果还是有报错,可以检查这几点:

  • 确保绘图时用到的所有列名,在CDS中都存在(别拼错petal_length这类原生列名)
  • 自定义字段要先在DataFrame中生成,再传入CDS
  • HoverTool的tooltips如果引用了不存在的字段,也会触发运行时错误

内容的提问来源于stack exchange,提问作者Shaumyabrata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:19:04