Bokeh添加图例触发ValueError:DataFrame真值判断模糊
解决Bokeh绘制折线图时的ValueError问题
这个错误的根源在于你混淆了Bokeh中指定图例的两种方式:当你通过source参数绑定了DataFrame作为数据源时,不能直接用legend参数传入列名,而是要用**legend_field**来指定数据源中的字段。
错误原因拆解
你写的legend='label'看起来是想把DataFrame里的label列作为图例文本,但Bokeh的legend参数只接受普通字符串(比如直接写legend='something')。当你传入列名时,Bokeh会尝试解析这个参数的真值,而DataFrame/Series的真值判断本身是模糊的(因为它是一个集合,不是单个布尔值),所以就触发了ValueError: The truth value of a DataFrame is ambiguous...这个错误。
修正后的代码
import pandas as pd from bokeh.plotting import figure, show d = {'col1': [1, 2], 'col2': [3, 4], 'label' : ['something', 'something']} df = pd.DataFrame(data=d) trend = figure(tools="pan,box_zoom,reset,save", title="trends") # 把legend改成legend_field,绑定数据源中的label列 trend.line(source=df, x='col1', y='col2', line_color="red", legend_field='label') # 注意:你原来的show(p)里的p是未定义的,应该是show(trend) show(trend)
额外说明
- 如果你的图例是固定文本(不需要从数据源读取),可以直接用
legend='自定义图例文本'; - 如果需要从数据源的某一列动态获取图例内容,必须用
legend_field='列名'; - 另外你代码里最后一行的
show(p)是笔误,变量名应该是trend,否则会触发NameError。
内容的提问来源于stack exchange,提问作者Barbara




