Python中的逐段绘制函数

2024-10-02 10:27:35 发布

您现在位置: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

但我没有正确使用这些函数,现在只是随机猜测如何做到这一点。

一些答案开始出现。。。但是这些点被连接成一条曲线。我们怎么画出点呢?

enter image description here


Tags: 函数importreturnifplotmatplotlibdefas
3条回答

Some answers are starting to get there... But the points are being connected into a line on the plot. How do we just plot the points?

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()

enter image description here

问题是函数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]))

相关问题 更多 >

    热门问题