[英]How do I plot a step function with 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 制作类似的图形?
从版本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)
您可以通过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)
情节:
希望对到达这里的人有所帮助。
这种类型的图表现在包含在库中。 您可以简单地使用Step功能。
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)
我写了一个使用 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)
当然,您可以将 output_notebook() 替换为您希望的任何输出格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.