如何在python的图形中绘制峰

时间:2019-03-18 17:09:03

标签: python numpy matplotlib plot

我试图将图形的峰添加到数组中并将其绘制在我的图中。这是我的代码:

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()

Picture of the graph

1 个答案:

答案 0 :(得分:1)

您只需使用衍生工具。在这里,我采用了几个渐变来确保我们找到的点在顶部,而不仅仅是a幸。

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()

输出: Plot with peaks shown 注意对于我的帖子,不需要像我这样的多余衍生工具。我之所以将它们包括在内,是因为您的数据集之间的数字差异可能很小,如果您仅与两个最接近的数字进行比较(实验数据中的常见数字),这些数字可能会错误地将某些数字标记为局部最大值。也可以采用类似的导数:

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]:

如果这对您更有意义,或者如果您仍然得到怪异的结果,甚至可以通过其他方式使用!