2017-04-09 219 views
0

我試圖在matplotlib中繪製分段函數。我的濾波方法(這是根據AMI的答案here)不工作:在python中繪製分段函數

ValueError: x and y must have same first dimension

你能解決這個問題嗎?

import numpy as np 
import matplotlib.pyplot as plt 

gK_inf = 7.06 
gK_0 = 0.09 
tauN = 0.75 

gK_inf1 = 0.09 
gK_01 = 7.06 
tauN1 = 1.1 

def graph(formula, formula1, t_range): 
    t = np.fromiter(t_range, np.float) 
    gK = formula(t) 
    gK1 = formula1(t) 
    plt.plot(t,gK) 
    plt.plot(t,gK1) 
    plt.xlabel(r"$t(msec.)$") 
    plt.ylabel(r"$g_K$") 
    plt.show() 

def my_formula(t): 
    if np.all(t>0) and np.all(t<5): 
     return np.power((np.power(gK_inf,0.25))-((np.power(gK_inf,0.25)-np.power(gK_0,0.25))*np.exp(-t/tauN)),4) 
    else: 
     return 0 

def my_formula1(t): 
    if np.all(t>5) and np.all(t<10): 
     return np.power((np.power(gK_inf1,0.25))-((np.power(gK_inf1,0.25)-np.power(gK_01,0.25))*np.exp(-t/tauN1)),4) 
    else: 
     return 0 

graph(my_formula, my_formula1, np.arange(0,10,0.1)) 

更新:

據@邁克爾的建議,錯誤被刪除,但結果是不是它必須是:

enter image description here

其實,formulaformula1必須分別繪製在範圍[0,5][5,10]

這就是我需要:

enter image description here

+0

更新中的情節是預期的輸出嗎?然後我不明白你爲什麼使用'np.all'和'return 0'來表示藍色曲線(t> 5時不會爲零)。請更詳細地指定您想要的內容(除了修復錯誤信息外)。 – Michael

+0

@邁克爾:你說得對。我的代碼的邏輯不是它應該是什麼。我添加了一張草圖來說明我需要什麼,如果你有興趣檢查它。 – Roboticist

+1

好,所以你想*一個*曲線。我想我現在明白了。我要試一下,然後編輯我的答案。 – Michael

回答

1

你應該return np.zeros_like(t)替換都my_formulareturn 0my_formula1。要求相同形狀的數組。隨着你的輸入數據np.arange(0,5,0.1),你總是會遇到這種情況return 0這是一個int。如果你想,你可以把它想象成一個形狀爲(1,)的數組(嚴格來說這不是真的,如果你嘗試0.shape會得到一個錯誤)。然後,您嘗試繪製一個具有50個x值的y值。儘管總是採取相同的y值似乎是合乎邏輯的,但這不是plt.plot的工作原理。當您使用np.zeros_like(t)時,您將得到一個包含50個零條目的數組,並且plt.plot知道要繪製什麼。


EDIT

根據該更新,我提出了這樣的:

import numpy as np 
import matplotlib.pyplot as plt 

gK_inf = 7.06 
gK_0 = 0.09 
tauN = 0.75 

gK_inf1 = 0.09 
gK_01 = 7.06 
tauN1 = 1.1 

def graph(formula, t_range): 
    t = np.fromiter(t_range, np.float) 
    gK = formula(t) 
    plt.plot(t,gK) 
    plt.xlabel(r"$t(msec.)$") 
    plt.ylabel(r"$g_K$") 
    plt.show() 

def my_formula(t): 
    result = np.power((np.power(gK_inf,0.25))-((np.power(gK_inf,0.25)-np.power(gK_0,0.25))*np.exp(-t/tauN)),4) *(t>=0)*(t<5) 
    result += np.power((np.power(gK_inf1,0.25))-((np.power(gK_inf1,0.25)-np.power(gK_01,0.25))*np.exp(-(t-5)/tauN1)),4) *(t>=5)*(t<=10) 
    return result 

graph(my_formula, np.arange(0.0,12,0.1)) 

施加一定的t值的公式決定與布爾數組(t>=0)*(t<5)(t>=5)*(t<=10) 。當它們與float數組相乘時,對於False1,它們被轉換爲0,對於True,因此它始終是所應用的t範圍的正確公式。我也改變了公式中的一些東西5 < = t < = 10:爲了使它看起來像你的預期輸出,我不得不改變指數函數:np.exp(-t/tauN1))被替換爲np.exp(-(t-5)/tauN1))

+0

謝謝。你能看看我的更新嗎?過濾方法根本不起作用。 – Roboticist

+0

在此先感謝您的幫助。 – Roboticist