如何在全息视图 + 散景中获得带有图例标签的 full-height 垂直线?

How do I get a full-height vertical line with a legend label in holoviews + bokeh?

我想在 holoviews 中用 bokeh 后端绘制一条垂直线,该后端有一个显示在我的图例中的标签。我需要这条线作为情节的完整高度,无论它是单独的还是与其他元素重叠。我怎样才能做到这一点?

例子

我在示例中添加了一个曲线图,否则即使是可以出现在图例中的元素也只是使用它们的标签作为标题。

import numpy as np
import holoviews as hv
hv.extension("bokeh")

x = np.linspace(0, 1)
curve = hv.Curve((x, np.sin(x)), label="sin(x)")
vline = hv.VLine(0.5, label="vline")
curve * vline

这给出了以下情节:

没有垂直线的标签。如何显示标签?

this issue but not yet in the docs, VLine and HLine don't appear in legends, and there is no plan to add support for them (basically, in bokeh they're created differently, so there's not an easy way to put them in the legend). One can use Spikes instead. However, as documented in another issue 中所述,尖峰无法很好地重叠。特别是,如果没有给出明确的高度,他们不会将自己的高度调整为地块的完整高度。这是我想出的两个解决方法。

解决方法 1

您可以明确找出应该覆盖垂直线的其他元素的高度,并使用它来创建适当高度的尖峰。这可行,但它相当脆弱,因为您需要在充分了解可能被尖峰覆盖的所有内容的情况下对其进行调整。

import numpy as np
import holoviews as hv
hv.extension("bokeh")

x = np.linspace(0, 1)
curve = hv.Curve((x, np.sin(x)), label="sin(x)")
height = curve.data["y"].max() - curve.data["y"].min()
spikes = hv.Spikes(([0.5], [height]), vdims="height", label="mid")
spikes * curve

解决方法 2

这同时使用了 VLineSpikes。尖峰将不可见,除非它会为图例提供一个条目。 vline 将位于尖峰的顶部,vline 已经自我调整以填充图形的整个高度。这需要创建一个额外的元素,但它更健壮,因为您可以将此尖峰和 vline 的乘积与任何其他元素叠加,并且仍然会得到一条填充绘图高度并出现在图例中的线。但是,由于图例条目基于尖峰,因此只有当您确保它们具有相似的外观(例如,vline 和尖峰具有相同的颜色)时,它才会看起来像 vline。

# need to make sure the colors are the same for spikes/vlines
# would look a bit better if I adjusted the spike thickness too
spikes = hv.Spikes([0.5], label="mid").opts(color="black")
vline = hv.VLine(0.5).opts(color="black")

spikes * curve * vline

将来,Spikes 希望在未明确指定高度时将自己缩放为全高,然后就不需要这些解决方法了。

基于 Nathans 2 解决方法,有第三种非常简单的解决方法使用 Curve

import numpy as np
import holoviews as hv
hv.extension("bokeh")

x = np.linspace(0, 1)
curve = hv.Curve((x, np.sin(x)), label="sin(x)")
height = (curve.data["y"].min(), curve.data["y"].max())
xpos = 0.5

spikes = hv.Curve(([xpos]*2, height), label="mid")
spikes * curve