I want to find maxima and minima from a list, but after running my program, terminal shows error like “ValueError: x and y must have same first dimension, but have shapes (1, 2) and (2,),”. How to fix this problem?
Code:
JavaScript
x
16
16
1
from scipy.signal import argrelextrema
2
3
data = np.array([-1, 0, 1, 2, 1, 0, -1, -2, -1, 0, 1, 2, 1 ])
4
plt.plot(data)
5
6
7
maximums = argrelextrema(data, np.greater)
8
9
plt.plot(maximums, data[maximums], "x")
10
11
minimums = np.array(argrelextrema(data, np.less))
12
13
plt.plot(minimums, data[minimums], ".")
14
15
plt.show()
16
Advertisement
Answer
As you can see in the documentation, maxima
and minima
are not 1 dimensional arrays but tuples of ndarrays
JavaScript
1
9
1
import numpy as np
2
from scipy.signal import argrelextrema
3
import matplotlib.pyplot as plt
4
5
data = np.array([-1, 0, 1, 2, 1, 0, -1, -2, -1, 0, 1, 2, 1 ])
6
7
maxima = argrelextrema(data, np.greater)
8
minima = argrelextrema(data, np.less)
9
let’s check
JavaScript
1
2
1
print(maxima)
2
gives
JavaScript
1
2
1
(array([ 3, 11]),)
2
and
JavaScript
1
2
1
print(minima)
2
gives
JavaScript
1
2
1
(array([7]),)
2
Since you need the first element only of the tuple, you can do
JavaScript
1
5
1
plt.plot(data)
2
plt.plot(maxima[0], data[maxima[0]], "x", ms=10)
3
plt.plot(minima[0], data[minima[0]], ".", ms=10)
4
plt.show()
5