散景中的无限水平线

Infinite horizontal line in Bokeh

有没有办法用 Bokeh 绘制无限水平线? 无论用户缩放多远,线的端点都不应该变得可见。

这是我目前尝试过的方法。它只是打印一个空的 canvas:

import bokeh.plotting as bk
import numpy as np

p = bk.figure()
p.line([-np.inf,np.inf], [0,0], legend="y(x) = 0")
bk.show(p)

一种方法是将端点设置得非常 high/low 并且图形的 x_range 和 y_range 相对于它们非常小。

import bokeh.plotting as bk
import numpy as np

p = bk.figure(x_range=[-10,10])
p.line([-np.iinfo(np.int64).max, np.iinfo(np.int64).max], [0,0], legend="y(x) = 0")
bk.show(p)

但是,我希望有人有更优雅的解决方案。

编辑:删除了过时的解决方案

如果您从中间绘制两条射线,它们不会随着您放大或缩小而变小,因为长度以像素为单位。所以像这样:

p.ray(x=[0],y=[0],length=300, angle=0, legend="y(x) = 0")
p.ray(x=[0],y=[0],length=300, angle=np.pi, legend="y(x) = 0")

但是如果用户向任一方向平移,光线的末端就会出现。如果您可以完全阻止用户平移(即使他们缩放),那么这对于水平线来说是一个更好的代码。

如果用户能够随心所欲地缩放和平移,则没有什么好的方法(据我所知)获得您描述的水平线。

Bokeh documentation on segments and rays表示如下解决方案(使用ray):

To have an “infinite” ray, that always extends to the edge of the plot, specify 0 for the length.

事实上,下面的代码产生了一条无限的水平线:

import numpy as np
import bokeh.plotting as bk
p = bk.figure()
p.ray(x=[0], y=[0], length=0, angle=0, line_width=1)
p.ray(x=[0], y=[0], length=0, angle=np.pi, line_width=1)
bk.show(p)

您正在寻找"spans":

Spans (line-type annotations) have a single dimension (width or height) and extend to the edge of the plot area.

请看一下 http://docs.bokeh.org/en/latest/docs/user_guide/annotations.html#spans

因此,代码将如下所示:

import numpy as np
import bokeh.plotting as bk
from bokeh.models import Span

p = bk.figure()

# Vertical line
vline = Span(location=0, dimension='height', line_color='red', line_width=3)
# Horizontal line
hline = Span(location=0, dimension='width', line_color='green', line_width=3)

p.renderers.extend([vline, hline])
bk.show(p)

有了这个解决方案,用户可以随意平移和缩放。行尾永远不会出现。

如果您想知道如何将跨度与时间序列结合使用,请将您的日期转换为 unix 时间戳:

start_date = time.mktime(datetime.date(2018, 3, 19).timetuple())*1000
vline = Span(location=start_date,dimension='height', line_color='red',line_width=3)

或查看 this link 以获取完整示例。