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

时间:2014-07-14 20:44:53

标签: python bokeh

在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创建类似的图形?

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以使用line以及对阵列进行一些手动操作。请注意y轴的interleaving of lists。此外,我们希望(我猜)稍微修改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)

情节:

example step plot w/ bokeh

希望能帮助到达这里的人。

答案 2 :(得分:-1)

此类图表现已包含在库中。您只需使用Step功能。

请参阅文档中的示例: http://bokeh.pydata.org/en/0.10.0/docs/gallery/step_chart.html

from collections import OrderedDict

from bokeh._legacy_charts import Step, show, output_file

xyvalues = OrderedDict(
    python=[2, 3, 7, 5, 26, 81, 44, 93, 94, 105, 66, 67, 90, 83],
    pypy=[12, 20, 47, 15, 126, 121, 144, 333, 354, 225, 276, 287, 270, 230],
    jython=[22, 43, 70, 75, 76, 101, 114, 123, 194, 215, 201, 227, 139, 160],
)


output_file("steps.html", title="line.py example")

chart = Step(xyvalues, title="Steps", ylabel='measures', legend='top_left')

show(chart)

答案 3 :(得分:-1)

我写过一个使用line的小函数,matplotlib风格比@ Brandt的答案多一点。在jupyter笔记本中,这是

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)

给你 enter image description here

当然,您可以将output_notebook()替换为您希望的任何输出格式。