运行Bokeh画廊示例代码时出现AttributeError:'Figure'对象无'hbar_stack'属性
解决Bokeh中'Figure' object has no attribute 'hbar_stack'的错误
这个错误我之前帮朋友排查过,核心原因就是你使用的Bokeh版本太老,不支持hbar_stack这个便捷方法。
先确认你的Bokeh版本
hbar_stack是在Bokeh 1.4.0版本里新增的功能,如果你的版本低于这个,就会触发这个AttributeError。你可以通过以下方式查看当前版本:
在Python脚本里运行:
import bokeh print(bokeh.__version__)
或者直接在终端执行命令:
bokeh --version
解决方案一:升级Bokeh到最新稳定版
这是最直接的解决办法,通过pip升级即可:
pip install --upgrade bokeh
升级完成后,把你代码里没写完的2017数据补全,就能正常运行了。这里给你补全后的完整可运行代码:
from bokeh.io import output_file, show from bokeh.models import ColumnDataSource from bokeh.palettes import GnBu3, OrRd3 from bokeh.plotting import figure output_file("bar_stacked_split.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] exports = { 'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 5, 3, 3] # 补全缺失的数值 } source = ColumnDataSource(data=exports) p = figure(y_range=fruits, height=250, x_range=(0, 16), title="Fruit exports by year") p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=source, legend_label=years) # 优化图表样式 p.y_range.range_padding = 0.1 p.ygrid.grid_line_color = None p.legend.location = "top_left" p.axis.minor_tick_line_color = None p.outline_line_color = None show(p)
解决方案二:无法升级时,手动实现堆叠水平条形图
如果因为环境依赖限制不能升级Bokeh版本,也可以手动计算每个堆叠层的起始位置,用基础的hbar方法逐个绘制:
from bokeh.io import output_file, show from bokeh.models import ColumnDataSource from bokeh.palettes import GnBu3, OrRd3 from bokeh.plotting import figure output_file("bar_stacked_split.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] exports = { 'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 5, 3, 3] } # 计算每个堆叠层的起始位置(前几层的总和) start_2015 = [0]*len(fruits) start_2016 = [exports['2015'][i] for i in range(len(fruits))] start_2017 = [exports['2015'][i] + exports['2016'][i] for i in range(len(fruits))] # 给数据源添加总和字段,方便绘制 exports['2015+2016'] = [a+b for a,b in zip(exports['2015'], exports['2016'])] exports['2015+2016+2017'] = [a+b+c for a,b,c in zip(exports['2015'], exports['2016'], exports['2017'])] source = ColumnDataSource(data=exports) p = figure(y_range=fruits, height=250, x_range=(0, 16), title="Fruit exports by year") # 逐个绘制堆叠的水平条形 p.hbar(y='fruits', left=start_2015, right='2015', height=0.9, color=GnBu3[0], source=source, legend_label='2015') p.hbar(y='fruits', left=start_2016, right='2015+2016', height=0.9, color=GnBu3[1], source=source, legend_label='2016') p.hbar(y='fruits', left=start_2017, right='2015+2016+2017', height=0.9, color=GnBu3[2], source=source, legend_label='2017') # 统一图表样式 p.y_range.range_padding = 0.1 p.ygrid.grid_line_color = None p.legend.location = "top_left" p.axis.minor_tick_line_color = None p.outline_line_color = None show(p)
内容的提问来源于stack exchange,提问作者Mithilesh
相关产品推荐
相关产品推荐

