【发布时间】:2015-10-16 18:39:59
【问题描述】:
我想使用 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
但我没有正确使用这些功能,现在只是随机猜测如何做到这一点。
一些答案开始出现......但是这些点被连接成情节上的一条线。我们如何绘制点?
【问题讨论】:
标签: python python-3.x numpy matplotlib