[英]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.