我正在尝试在python中进行曲线拟合,并且遇到了一个奇怪的错误。我不确定这个错误的起源是什么。当我以1而不是0.1的步长绘制时,我有这一步。有人可以指出我为什么会收到此错误。
import numpy as np
from matplotlib import pyplot as plt
coeff = [0.6e-4, 0.48e-3, -0.29e-2, -0.164, -0.400, -0.472, -0.330, -0.057, 0.306, 0.689, 1.061, 1.406, 1.715, 1.986, 2.223, 2.432, 2.616]
Temp = [5, 10, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300]
coeff = [0, 0, 0, -0.164, -0.400, -0.472, -0.330, -0.057, 0.306, 0.689, 1.061, 1.406, 1.715, 1.986, 2.223, 2.432, 2.616]
Temp = [5, 10, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300]
legends = np.polyfit(Temp,coeff,4)[::-1]
T = np.arange(4,300,1)
y = [sum([float(a*x**y) for y,a in enumerate(legends)]) for x in T]
T_ = np.arange(4,300,0.1)
y_ = [sum([a*x**y for y,a in enumerate(legends)]) for x in T_]
plt.figure()
plt.plot(Temp,coeff,"ko")
plt.plot(T,y,"ro")
plt.plot(T_,y_,"go")
plt.show()
答案 0 :(得分:0)
当我运行你的代码时,我收到了消息
Traceback (most recent call last):
File "test.py", line 26, in <module>
plt.plot(T,y,"ro")
File "/astromake/opt/casa/stable/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2458, in plot
ret = ax.plot(*args, **kwargs)
File "/astromake/opt/casa/stable/lib/python2.7/site-packages/matplotlib/axes.py", line 3848, in plot
for line in self._get_lines(*args, **kwargs):
File "/astromake/opt/casa/stable/lib/python2.7/site-packages/matplotlib/axes.py", line 323, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "/astromake/opt/casa/stable/lib/python2.7/site-packages/matplotlib/axes.py", line 300, in _plot_args
x, y = self._xy_from_xy(x, y)
File "/astromake/opt/casa/stable/lib/python2.7/site-packages/matplotlib/axes.py", line 240, in _xy_from_xy
raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension
这告诉您代码在第26行失败,原因是T和y的类型不同。这是真的:T是np.array,而y是列表。您可以通过在y:
上调用np.asarray()来解决此问题y = np.asarray([sum([float(a*x**y) for y,a in enumerate(legends)]) for x in T])
和
y_ = np.asarray([sum([a*x**y for y,a in enumerate(legends)]) for x in T_])
顺便说一下,我做了一个快速的谷歌搜索,发现了this问题,基本上也给出了问题的答案。
答案 1 :(得分:0)
问题是,在分配y
和enumerate()
时,您正在重复y
变量名称(在y_
中),以便在您进行绘图时,y
不再与x
形状相同。
尝试:
T = np.arange(4,300,1)
y = [sum([float(a*x**m) for m,a in enumerate(legends)]) for x in T] # note the change from y -> m
T_ = np.arange(4,300,0.1)
y_ = [sum([a*x**n for n,a in enumerate(legends)]) for x in T_] # note the change from y -> n