Search code examples
pythonarraysplotfloating-pointdimensions

How to solve array dimension error when plotting?


Based on the code below, I am trying to plot array_frequency_a vs. power_a, but am receiving this error:

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

I know this means that my arrays are different sizes, but how can I change them or create power_a in a different way so that they can be plotted against each other? Thanks!

frequency_a=[]
dB_a=[]

a = csv.reader(open('Air.csv'))

for row in itertools.islice(a, 18, 219):
       frequency_a.append(float(row[0]))
       dB_a.append(float(row[1]))
       #print(frequency_a)
array_frequency_a = np.array(frequency_a)       
array_dB_a = np.array(dB_a)

#perform operation on data
for i in range(201):
    power_a = np.array(10**(array_dB_a[i]/10))
    print(power_a)

fig, ax = plt.subplots()
ax.plot(array_frequency_a/1e9, power_a, 'b', label='1in air.')

Solution

  • I think you want to apply some transformation to array_dB_a and then plot against the transformed array. One way to do it more efficiently is to map the function to the array by using np.vectorize:

    power_f = lambda t: 10 ** (t / 10)
    vfunc = np.vectorize(power_f)
    new_array_dB_a = vfunc(array_dB_a)
    

    Then you the new array will have the same dimensions as array_frequency_a:

    fig, ax = plt.subplots()
    ax.plot(array_frequency_a/1e9, new_array_dB_a, 'b', label='1in air.')