本文介绍了在Python中绘制分段函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Matplotlib在Python中从0到5绘制以下分段函数.
I would like to plot the following piecewise function in Python using Matplotlib, from 0 to 5.
f(x) = 1, x != 2; f(x) = 0, x = 2
在Python中...
In Python...
def f(x):
if(x == 2): return 0
else: return 1
使用NumPy创建一个数组
Using NumPy I create an array
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
但是我没有正确使用这些功能,现在只是随机猜测如何做到这一点.
But I am not using these functions correctly, and am now just randomly guessing how to do this.
一些答案开始到达那里...但是这些点已连接到绘图上的一条线中.我们如何绘制点?
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()
这篇关于在Python中绘制分段函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!