這應該很簡單,但我剛開始玩matplotlib和python。我可以做一個線或散點圖,但我不知道如何做一個簡單的步驟功能。任何幫助深表感謝。如何在Python中使用Matplotlib繪製一個步驟函數?
x = 1,2,3,4
y = 0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325
這應該很簡單,但我剛開始玩matplotlib和python。我可以做一個線或散點圖,但我不知道如何做一個簡單的步驟功能。任何幫助深表感謝。如何在Python中使用Matplotlib繪製一個步驟函數?
x = 1,2,3,4
y = 0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325
看來你想要。
E.g.
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()
謝謝!有用。任何方式擺脫垂直線? – rhm2012
好吧,如果你不想要任何垂直線,可以看看'plt.hlines'。例如。 'plt.hlines(y,範圍(1,5),範圍(2,6))' –
@Joe Kington:對不起一年後的評論。我對此有點困惑。不應該在1和2之間顯示0.0028,然後在2跳到0.051,依此類推?它看起來像step一樣使用下一個值。 (我正在考慮一個時間序列的步驟,其中值爲t0並且一直保持到t1,當它變爲b等等。)有沒有辦法讓step()以這種方式運行。 –
只是繪製兩條線,一條在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
的杆法。如果沒有結賬gallery你可以做很多樣式的地塊。每個圖像都帶有示例代碼,向您展示如何使用matplotlib製作它。
如果您有非均勻間隔的數據點,您可以使用drawstyle
關鍵字參數爲plot
:
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
。
很好。我用它來做其他事情。簡單而精確。 – Jerry
['drawstyle'文檔鏈接](http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_drawstyle)。 _「'steps'相當於'steps-pre',並保持向後兼容。」_ –
@VanniTotaro謝謝;我已經更新了答案。 –
如果有人只是想stepify一些數據,而不是實際繪製它:
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
一直在尋找一個內置函數沒有成功。謝謝!我有一個問題(由於版本?):TypeError:'zip'對象不可下載。我正在使用Python 3.5。該功能後,我更改所有的zip列表(zip(...))。 – Daniel
@丹尼爾感謝您的注意!我編寫了python 2的代碼,以便解釋錯誤。 –
你說的階躍函數是什麼意思?像直方圖? – wim
@wim https://en.wikipedia.org/wiki/Step_function – Galen