Search code examples
pythonmatplotlibvalueerror

What does the valueError mean?


Hi I'm trying to make a plot in python, but i get the error:

ValueError: x and y must have same first dimension, but have shapes (1,) and (50,)

This is the code over

L0 = 5.2 # [m]
v = np.linspace(0,2,50) 

Eks = []
Lin = []
x= np.array(vertikalForskyvning)
for vertikalForskyvning in range(50):
    L_eks = L0*np.sqrt(1+((24/L0)*(v/L0))+(v/L0)**2)
    L_lin = L0*(1+((12/13)*(v/L0)))
    DL_eks = L_eks-L0
    DL_lin = L_lin-L0
    Eks.append(L_eks)
    Lin.append(L_lin)

print(f"Eksakt forlengelse: {DL_eks}")
print(f"Linealisert forlengelse: {DL_lin}")

plt.plot(vertikalForskyvning, Eks)
plt.plot(vertikalForskyvning, L_lin)
plt.xlabel("Vertikalforsyvning [m]")
plt.ylabel("Delta L [m]")
plt.legend(["Eksakt","Linearisert"])
plt.title("Forelngelse av stag")
plt.show()

Thank you for any help :)


Solution

  • after commenting out x= np.array(vertikalForskyvning), vertikalForskyvning is simply an iterator. The for loop then generates your lists for Eks and Lin. From the docs, plot is expecting two lists: (x,y). You are passing the end of your iterator (an int with a value at the end of your range(50) and a list. Instead replace the two lines with plot.plot(...) with:

    plt.plot(x = Eks,y = Lin)
    

    or perhaps:

    plt.scatter(x = Eks,y = Lin)
    

    scatter_plot