Python – keep on getting “x and y must have same first dimension, but have shapes (100,) and (1, 100)”

colorbarfor-loopmatplotlibplotpython

I have been trying to create a plot with a colourbar, with a code that I have previously used, but this time I changed the equation that represents the values for the y-axis. The code is below:

import numpy as np
import matplotlib
import matplotlib as plt


θ= [0.01, 1, 2, 3, 4, 5] #values for the colourbar to use in equation in for loop
x=np.linspace[0.1, 8, 100]
y=1/(np.exp(x)+1)       #factor used in equation dependent on the x-axis values
a=(5.3)*10**4           # constant for the equation

norm = matplotlib.colors.Normalize(vmin=np.min(θ), vmax=np.max(θ))  #colourbar max and min values
c_m = matplotlib.cm.cool
s_m = matplotlib.cm.ScalarMappable(cmap='jet', norm=norm)

s_m.set_array([])

#below is the for loop that uses one value of θ at a time, represented as t in the equation


for t in θ:            
    plt.plot(x, a*y*x*[np.pi/(4*x) - (np.arctan(x*t**3)+ (t**3)/(1 + (t**6) * x**2))], color=s_m.to_rgba(t)) 

func = lambda x,pos: "{:g}".format(x *100000)
fmt = matplotlib.ticker.FuncFormatter(func)

c_bar=plt.colorbar(s_m, format=fmt)

plt.legend()
plt.xlabel('y=E/T')
plt.ylabel('$f_{ν_s}$')
c_bar.set_label(r'$ \theta \times 10^{-5}$ rads')
plt.show()

The problem with this code, is that it constantly gives me the following error message:

"x and y must have same first dimension, but have shapes (100,) and (1, 100)"

I have checked the equations multiple times but I still don't understand what is wrong. Initially I thought that changing my x-range not to have 0 as its lowest limit would do the trick, but it did not and the same message appears.

I have looked into questions with a similar problem (Matplotlib: ValueError: x and y must have same first dimension) but I'm still unable to solve this problem

Best Solution

Several issue with your script. The one that is causing the dimensions error is that you are using square brackets in your call to plt.plot. This creates a list, and multiplies it by the a*y*x term, giving a shape of [1, 100].

So, change

a*y*x*[np.pi/(4*x) - (np.arctan(x*t**3)+ (t**3)/(1 + (t**6) * x**2))]

to

a*y*x*(np.pi/(4*x) - (np.arctan(x*t**3)+ (t**3)/(1 + (t**6) * x**2)))

Note you also use square brackets when you create x using linspace when you should use x=np.linspace(0.1, 8, 100).

And finally, your module imports are a little strange. You need to have

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm

and then use cm.cool and cm.ScalarMappable

Related Question