How To Label Peaks In Python

In this tutorial, we will learn how to label peaks in a dataset using Python. This skill is useful, especially for those doing scientific research or working with data analysis where finding and labeling peaks in data is essential. We will use popular libraries like Matplotlib, NumPy, and SciPy to plot and label the peaks.

Requirements

Before we start, make sure you have the following libraries installed:

  1. Matplotlib – A Python library used for creating static, interactive, and animated visualizations in Python.
  2. NumPy – A Python library used for working with arrays and performing numerical computations.
  3. SciPy – A Python library used for scientific and technical computing tasks.

To install the libraries, open your terminal or command prompt and run the following command:
pip install matplotlib numpy scipy

Step 1: Import the necessary libraries

First, let’s import the necessary libraries:

Step 2: Create sample data

Now, let’s create some sample data for demonstration purposes. You can replace this with your dataset if you wish.

Here, we create an array x with 100 equally-spaced points between 0 and 10. For y, we generate a noisy exponential decaying sine wave.

Step 3: Find the peaks in the data

Next, we will use SciPy’s find_peaks function to identify the peak indices in our dataset. This function returns the indices of the peaks in the data.

The find_peaks function takes several parameters. In this case, we have used prominence and width. Prominence is a measure of the relative height of the peak, while width is the width of the peak.

The find_peaks function returns two variables:
1. peaks – Array of indices where the peaks are located in the data.
2. properties – A dictionary containing information about the properties of the detected peaks.

Step 4: Plot the data and label the peaks

Now that we have identified the peaks in the dataset, let’s plot the data and label the peaks.

In the above code, we use Matplotlib to create a simple line plot of the data (x and y). The peaks are indicated by red dots using the plt.plot function. We then enumerate through the detected peaks and add a label for each peak using the plt.text function. Lastly, we add axis labels and a title to our plot.

Running this code will display the plot with the labeled peaks.

Full Code

Output

Conclusion

Congratulations! You have now learned how to label peaks in a dataset using Python with the help of Matplotlib, NumPy, and SciPy libraries. This skill is particularly useful when analyzing data, as it allows you to quickly and easily identify and highlight key features in your dataset.