[英]Plot Piecewise Function in Python
我想使用 Matplotlib 在 Python 中繪制以下分段函數,從 0 到 5。
f(x) = 1, x != 2; f(x) = 0, x = 2
在 Python 中...
def f(x):
if(x == 2): return 0
else: return 1
使用 NumPy 我創建一個數組
x = np.arange(0., 5., 0.2)
array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8, 2. ,
2.2, 2.4, 2.6, 2.8, 3. , 3.2, 3.4, 3.6, 3.8, 4. , 4.2,
4.4, 4.6, 4.8])
我嘗試過諸如...
import matplotlib.pyplot as plt
plt.plot(x,f(x))
或者...
vecfunc = np.vectorize(f)
result = vecfunc(t)
或者...
def piecewise(x):
if x == 2: return 0
else: return 1
import matplotlib.pyplot as plt
x = np.arange(0., 5., 0.2)
plt.plot(x, map(piecewise, x))
ValueError: x and y must have same first dimension
但是我沒有正確使用這些功能,現在只是隨機猜測如何做到這一點。
一些答案開始出現......但這些點正在連接成情節上的一條線。 我們如何只繪制點?
一些答案開始出現......但這些點正在連接成情節上的一條線。 我們如何只繪制點?
import matplotlib.pyplot as plt
import numpy as np
def f(x):
if(x == 2): return 0
else: return 1
x = np.arange(0., 5., 0.2)
y = []
for i in range(len(x)):
y.append(f(x[i]))
print x
print y
plt.plot(x,y,c='red', ls='', ms=5, marker='.')
ax = plt.gca()
ax.set_ylim([-1, 2])
plt.show()
問題是函數f
不接受一個數組作為輸入,而是一個單一的數字。 你可以:
plt.plot(x, map(f, x))
map
函數接受一個函數f
,一個數組x
並返回另一個數組,其中函數f
應用於數組的每個元素。
您可以在數組上使用np.piecewise :
x = np.arange(0., 5., 0.2)
import matplotlib.pyplot as plt
plt.plot(x, np.piecewise(x, [x == 2, x != 2], [0, 1]))
附加工作但需要一些額外的處理。 np 的分段工作正常。 可以對任何函數執行此操作:
`
import math
import matplotlib as plt
xs=[]
xs=[x/10 for x in range(-50,50)] #counts in tenths from -5 to 5
plt.plot(xs,[f(x) for x in xs])
`
如果您使用的是 python 2.x,則 map() 返回一個列表。 所以你可以這樣寫代碼:
import matplotlib.pyplot as plt
import numpy as np
def f(t):
if t < 10:
return 0;
else:
return t * t - 100;
t = np.arange(0, 50, 1)
plt.plot(t, map(f, t), 'b-')
plt.show()
如果您使用的是 python 3.x,則 map() 返回一個迭代器。 所以將地圖轉換為列表。
plt.plot(t, list(map(f, t)), 'b-')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.