Reputation: 397
I'm trying to add the peaks of a graph into an array and plot them in my figure. Here's my code:
import matplotlib.pyplot as plt
import numpy as np
t,x,y = np.loadtxt(r"C:\Users\haako\Documents\NTNU\Fysikk\Python\film2.txt", delimiter=' ', unpack=True)
plt.plot(t,x)
plt.xlabel("t-value")
plt.ylabel("x-value")
plt.show()
Upvotes: 0
Views: 2215
Reputation: 5774
You just take the derivative. Here I have taken several gradients to ensure that the point we find is at the top and not just a fluke:
import math
import matplotlib.pyplot as plt
x_array = []
y_array = []
for num in range(0, 10000):
x = num/100
y = math.sin(x) * (.99 ** x)
x_array.append(x)
y_array.append(y)
x_maximums = []
y_maximums = []
for i in range(2, len(y_array) - 2):
if y_array[i - 2] < y_array[i - 1] and y_array[i - 1] < y_array[i] and y_array[i + 2] < y_array[i + 1] and y_array[i + 1] < y_array[i]:
y_maximums.append(y_array[i])
x_maximums.append(x_array[i])
plt.plot(x_array, y_array)
plt.scatter(x_maximums, y_maximums, color='k')
plt.show()
Outputs:
NOTE The redundant derivatives like I took are not necessary for my post. I've included them because it's possible that your set of data has small variations between the numbers that would incorrectly mark some as being local maximum if you only compared to the two nearest numbers (Common in experimental data). Can alternatively take the derivatives like:
if y_array[i - 2] < y_array[i] and y_array[i - 1] < y_array[i] and y_array[i + 2] < y_array[i] and y_array[i + 1] < y_array[i]:
If that makes more sense to you, or maybe even in some other way if you are still getting weird results!
Upvotes: 1