0

I'm trying to make a Python app that shows a graph after the input of the data by the user, but the problem is that the y_array and the x_array do not have the same dimensions. When I run the program, this error is raised:

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

How can I draw a graph with the X and Y axis of different length?

Here is a minimal example code that will lead to the same error I got :

import matplotlib.pyplot as plt

y = [0, 8, 9, 3, 0]
x = [1, 2, 3, 4, 5, 6, 7]

plt.plot(x, y)
plt.show()
t.o.
  • 832
  • 6
  • 20
  • 1
    It's good that you have your code available, but it'd make the job of answering your question faster and easier if you provided a [minimal working example](https://stackoverflow.com/help/minimal-reproducible-example). For example, type up a test plot with the two arrays of differing size and reproduce your error with this. If it is as simple as making differing array sizes to match, there is an answer for interpolation [here](https://stackoverflow.com/questions/38064697/interpolating-a-numpy-array-to-fit-another-array) – t.o. May 25 '22 at 19:26
  • 1
    I'm sorry. Thanks for the advice, I have modified the question with a more legible code. – NyctalusNoctula May 25 '22 at 21:06

1 Answers1

1

This is virtually a copy/paste of the answer found here, but I'll show what I did to get these to match.

First, we need to decide which array to use- the x_array of length 7, or the y_array of length 5. I'll show both, starting with the former. Note that I am using numpy arrays, not lists.

Let's load the modules

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp

and the arrays

y = np.array([0, 8, 9, 3, 0])
x = np.array([1, 2, 3, 4, 5, 6, 7])

In both cases, we use interp.interp1d which is described in detail in the documentation.

For the x_array to be reduced to the length of the y_array:

x_inter = interp.interp1d(np.arange(x.size), x)
x_ = x_inter(np.linspace(0,x.size-1,y.size))

print(len(x_), len(y))
# Prints 5,5

plt.plot(x_,y)
plt.show()

Which gives

x_array

and for the y_array to be increased to the length of the x_array:

y_inter = interp.interp1d(np.arange(y.size), y)
y_ = y_inter(np.linspace(0,y.size-1,x.size))

print(len(x), len(y_))
# Prints 7,7
plt.plot(x,y_)
plt.show()

Which gives

y_array

t.o.
  • 832
  • 6
  • 20