Matplotlib和Python在两个维度上循环

时间:2017-11-01 17:45:49

标签: python arrays loops numpy matplotlib

我想要绘制6条三次多项式曲线。我有以下代码::

import numpy as np
import matplotlib.pyplot as plt 

a0 = np.array([ 0.04438, -0.01808, -0.01836,  0.01170, -0.01062, -0.01062])
a1 = np.array([-2.26095, -0.13595, -0.03577, -0.00400, -0.03577, -0.00400])
a2 = np.array([-0.13387,  0.01941,  0.02612,  0.00066,  0.02612,  0.00066])
a3 = np.array([ 0.00066, -0.00183, -0.00558, -0.00558,  0.00890,  0.00890])

x_max = 2.80
x_min = 0.30
diff  = 0.01

y = int(((x_max - x_min)/diff))
m_diff = np.zeros((y,6))

xmin = int(x_min * 100)
xmax = int(x_max * 100)
di   = int(diff  * 100)

for xx in range(xmin, xmax, di):
   x = xx*diff
   m_diff[xx] = a0 + (a1*x) + (a2*x*x) + (a3*x*x*x)

为什么我会收到“IndexError:索引250超出轴0的大小为250”错误?这应该是什么?最后我想做的就是:

plt(xx, m_diff[:,0])
plt(xx, m_diff[:,1])
plt(xx, m_diff[:,2])
plt(xx, m_diff[:,3])
plt(xx, m_diff[:,4])
plt(xx, m_diff[:,5])

谢谢!

2 个答案:

答案 0 :(得分:1)

这是矢量方法,可以防止数组形状出错:

x=np.arange(x_min,x_max,diff)
xs=np.power.outer(x,range(4))
coeffs=np.vstack((a0,a1,a2,a3))
curves=np.dot(xs,coeffs)
plt.plot(x,curves)

你只需要学习尺寸,一切都很简单;):

for array in x,xs,coeffs,curves : print (array.shape) 
# (250,)
# (250, 4)
# (4, 6)
# (250, 6)

结果:documentation

答案 1 :(得分:1)

Numpy有一个函数numpy.polyval来评估多项式。在这种情况下,您可以使用它来绘制多项式

import numpy as np
import matplotlib.pyplot as plt 

a0 = np.array([ 0.04438, -0.01808, -0.01836,  0.01170, -0.01062, -0.01062])
a1 = np.array([-2.26095, -0.13595, -0.03577, -0.00400, -0.03577, -0.00400])
a2 = np.array([-0.13387,  0.01941,  0.02612,  0.00066,  0.02612,  0.00066])
a3 = np.array([ 0.00066, -0.00183, -0.00558, -0.00558,  0.00890,  0.00890])

x_max = 2.80
x_min = 0.30
diff  = 0.01

coeff = np.c_[a3,a2,a1,a0]

x = np.arange(x_min,x_max,diff)
y = np.array([np.polyval(coeff[i],x) for i in range(coeff.shape[0])])

plt.plot(x,y.T)

plt.show()

enter image description here