[英]How do I plot a step function with Matplotlib in Python?
這應該很容易,但我剛剛開始玩弄 matplotlib 和 python。 我可以畫一條線或一個散點圖,但我不知道如何做一個簡單的階躍函數。 任何幫助深表感謝。
x = 1,2,3,4
y = 0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325
看起來你想要step
。
例如
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()
如果您有非均勻間隔的數據點,您可以為plot
使用drawstyle
關鍵字參數:
x = [1,2.5,3.5,4]
y = [0.002871972681775004, 0.00514787917410944,
0.00863476098280219, 0.012003316194034325]
plt.plot(x, y, drawstyle='steps-pre')
還可以使用steps-mid
和steps-post
。
有一個新的plt.stairs
方法來補充plt.step
:
plt.stairs
和底層StepPatch
提供了一個更清晰的界面,用於為您知道階梯邊緣的常見情況繪制逐步常數函數。這取代了
plt.step
許多用例,例如在繪制np.histogram
的輸出時。
查看官方 matplotlib 庫了解如何使用plt.stairs
和StepPatch
。
plt.step
與plt.stairs
如果您有參考點,請使用原始plt.step
。 這里的步驟錨定在[1,2,3,4]
並向左擴展:
plt.step(x=[1,2,3,4], y=[20,40,60,30])
如果您有edge ,請使用新的plt.stairs
。 前面的[1,2,3,4]
步點對應於[1,1,2,3,4]
樓梯邊緣:
plt.stairs(values=[20,40,60,30], edges=[1,1,2,3,4])
plt.stairs
和np.histogram
由於np.histogram
返回邊緣,它直接與plt.stairs
一起plt.stairs
:
data = np.random.normal(5, 3, 3000)
bins = np.linspace(0, 10, 20)
hist, edges = np.histogram(data, bins)
plt.stairs(hist, edges)
畫兩條線,一條在 y=0 處,一條在 y=1 處,在您的階躍函數用於的任何x
處切斷。
例如,如果您想在x=2.3
處從 0 步到 1 並從x=0
到x=5
繪圖:
import matplotlib.pyplot as plt
# _
# if you want the vertical line _|
plt.plot([0,2.3,2.3,5],[0,0,1,1])
#
# OR:
# _
# if you don't want the vertical line _
#plt.plot([0,2.3],[0,0],[2.3,5],[1,1])
# now change the y axis so we can actually see the line
plt.ylim(-0.1,1.1)
plt.show()
我想你想要pylab.bar(x,y,width=1)
或同樣pyplot
的 bar 方法。 如果沒有,請查看畫廊以了解您可以執行的多種樣式的繪圖。 每個圖像都帶有示例代碼,向您展示如何使用 matplotlib 制作它。
如果有人只是想對一些數據進行步進化而不是實際繪制它:
def get_x_y_steps(x, y, where="post"):
if where == "post":
x_step = [x[0]] + [_x for tup in zip(x, x)[1:] for _x in tup]
y_step = [_y for tup in zip(y, y)[:-1] for _y in tup] + [y[-1]]
elif where == "pre":
x_step = [_x for tup in zip(x, x)[:-1] for _x in tup] + [x[-1]]
y_step = [y[0]] + [_y for tup in zip(y, y)[1:] for _y in tup]
return x_step, y_step
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.