Skip to main content
 首页 » 编程设计

python之为什么 Bokeh 不在这里生成额外的 y 范围

2025年05月04日20qlqwjy

我的 Bokeh 版本是 0.12.13 和 Python 3.6.0 我修改了此处提供的示例代码:

https://docs.bokeh.org/en/latest/docs/user_guide/plotting.html

我刚刚尝试添加一个额外的 y 范围。

from bokeh.plotting import output_file, figure, show 
from bokeh.models import LinearAxis, Range1d 
 
x = [1,2,3,4,5] 
y = [1,2,3,4,5] 
y2 = [10,9,8,7,6] 
y3 = [23,24,25,26,27] 
 
output_file("twin_axis.html") 
 
p = figure(x_range=(0,6), y_range=(0,6)) 
 
p.circle(x, y, color="red") 
 
p.extra_y_ranges = {"foo1": Range1d(start=0, end=11)} 
p.circle(x, y2, color="blue", y_range_name="foo1") 
p.add_layout(LinearAxis(y_range_name="foo1"), 'left') 
 
p.extra_y_ranges = {"foo2": Range1d(start=21, end=31)} 
p.circle(x, y3, color="green", y_range_name="foo2") 
p.add_layout(LinearAxis(y_range_name="foo2"), 'right') 
 
p.toolbar_location ="above" 
show(p) 

虽然原始代码运行良好,但我修改后的代码却不行。我无法弄清楚我在做什么错误。我对 Bokeh 有点陌生,所以请指导我正确的方向。 编辑:当我添加第三个 y 轴时没有输出。但它仅适用于左侧的 2 个轴。

请您参考如下方法:

问题是您不是添加另一个 y 范围 — 通过将新字典重新分配给 p.extra_y_ranges,您是 < strong>完全替换旧的。当您添加的轴期望 "foo1" 范围存在时,这会导致问题,但您已将其吹走。以下代码按预期工作:

from bokeh.plotting import output_file, figure, show 
from bokeh.models import LinearAxis, Range1d 
 
x = [1,2,3,4,5] 
y = [1,2,3,4,5] 
y2 = [10,9,8,7,6] 
y3 = [23,24,25,26,27] 
 
output_file("twin_axis.html") 
 
p = figure(x_range=(0,6), y_range=(0,6)) 
 
p.circle(x, y, color="red") 
 
p.extra_y_ranges = {"foo1": Range1d(start=0, end=11)} 
p.circle(x, y2, color="blue", y_range_name="foo1") 
p.add_layout(LinearAxis(y_range_name="foo1"), 'left') 
 
# CHANGES HERE: add to dict, don't replace entire dict 
p.extra_y_ranges["foo2"] = Range1d(start=21, end=31) 
 
p.circle(x, y3, color="green", y_range_name="foo2") 
p.add_layout(LinearAxis(y_range_name="foo2"), 'right') 
 
p.toolbar_location ="above" 
show(p)