如何使用Bokeh绘制阶梯函数?

3 投票
3 回答
3379 浏览
提问于 2025-04-18 13:19

在matplotlib中,要画一个阶梯函数,你可以写类似这样的代码:

import matplotlib.pyplot as plt

x = [1,2,3,4] 
y = [0.002871972681775004, 0.00514787917410944, 
     0.00863476098280219, 0.012003316194034325]

plt.step(x, y)
plt.show()

那我该怎么用Bokeh来画一个类似的图呢?

3 个回答

-1

我写了一个小函数,用来实现这个功能,风格上更接近matplotlib,而不是@Brandt的答案。在jupyter notebook中,这段代码是

def step(fig, xData, yData, color=None, legend=None):
    xx = np.sort(list(xData) + list(xData))
    xx = xx[:-1]
    yy = list(yData) + list(yData)
    yy[::2] = yData
    yy[1::2] = yData
    yy = yy[1:]
    fig.line(xx, yy, color=color, legend=legend)
    return fig
# example
import bokeh.plotting as bok
import bokeh
bokeh.io.output_notebook()

x = [1,2,3,4]
y = [0.002871972681775004, 0.00514787917410944, 
     0.00863476098280219, 0.012003316194034325]
f = bok.figure()
f = step(f, x, y)
bok.show(f)

运行后会给你这个结果:

这里是图片描述

当然,你可以把output_notebook()替换成你想要的任何输出格式。

0

你可以通过使用 line 和对数组进行一些手动操作来实现这个功能。记得要考虑一下 将两个列表交错,特别是在处理 y 轴的时候。此外,我们可能还需要稍微调整一下 x 轴的值,以便设置左右的限制。让我给你提供以下内容:

from bokeh.plotting import figure
import numpy as np
f = figure()
#
# Example vectors (given):
x = [1,2,3,4]
y = [0.002871972681775004, 0.00514787917410944, 
     0.00863476098280219, 0.012003316194034325]
#
_midVals = np.diff(x)/2.0
xs = set(x[:-1]-_midVals).union(x[1:]+_midVals)
xl = list(xs)
xl.sort()
xx = xl[1:]+xl[:-1]
xx.sort()
yy = y+y
yy[::2] = y
yy[1::2] = y
#
# assert/print coordinates
assert len(xx)==len(yy)
for _p in zip(xx,yy):
    print _p
#
# Plot!
f.line(x=xx, y=yy)
show(f)

我们这个 "合理性检查" 的输出应该是:

(0.5, 0.002871972681775004)
(1.5, 0.002871972681775004)
(1.5, 0.00514787917410944)
(2.5, 0.00514787917410944)
(2.5, 0.00863476098280219)
(3.5, 0.00863476098280219)
(3.5, 0.012003316194034325)
(4.5, 0.012003316194034325)

还有这个图表:

示例步骤图 w/ bokeh

希望这些对来到这里的人有所帮助。

5

Bokeh 从版本 0.12.11 开始,内置了一个叫做 Step 的图形元素:

from bokeh.plotting import figure, output_file, show

output_file("line.html")

p = figure(plot_width=400, plot_height=400)

# add a steps renderer
p.step([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2, mode="center")

show(p)

enter image description here

撰写回答