Home > Enterprise >  ValueError: x and y must have same first dimension, but have different shapes
ValueError: x and y must have same first dimension, but have different shapes

Time:11-11

I am currently trying to fit some measurement data into three polynomial functions of the degrees 1, 2, and 3.

My code is as follows:

ylist = [81, 50, 35, 27, 26, 60, 106, 189, 318, 520]
y = np.array(ylist)
t = np.linspace(-0.9,0.9,10)

p1 = np.polyfit(t,y,1)
p2 = np.polyfit(t,y,2)
p3 = np.polyfit(t,y,3)

pp1 = np.poly1d(p1) #saw online that using poly1d would be helpful when working with polynomials, not sure if it's entirely necessary in my case
pp2 = np.poly1d(p2)
pp3 = np.poly1d(p3)

I then tried to plot both the polyfit graphs and the poly1d graphs like this (I first tried plotting p1,p2,p3, but got a ValueError, so I thought plotting pp1,pp2,pp3 would work):

plt.plot(t,y,'o')
plt.plot(t,p1)
plt.plot(t,pp1)

But the problem is, when I try to plot my polynomials, python gives out the error:

ValueError: x and y must have same first dimension, but have shapes (10,) and (2,)

The way I understand it, python cannot plot my polynomials with my t data because t has 10 points, while my polynomials only have 2, but shouldn't polyfit (or poly1d) give me a graph? Do I need to plot it with an entirely different x axis data?

I'm still very new to python, any help is appreciated!

CodePudding user response:

pp1 is a poly1d object. So, you need to call it for each of your t values to get the corresponding values of the fit. Something like

fit_vals = [pp1(curr_t) for curr_t in t]
plt.plot(t, fit_vals)

Should work

  • Related