Home > other >  Trying to iterate through arrays and annotate them
Trying to iterate through arrays and annotate them

Time:11-01

I'm plotting graphs and I want to plot the values of the peaks which I've found using scipy. Now i have 2 numpy arrays that are the x values and y values of each peak. I want to go through these peaks and annotate all that are between the chosen x limits (xlim) as I plot both the full x and a zoom in of the peaks.

I've tried to just annotate all the values but I can't get that to work.

for i in x[0:-1]:
     plt.annotate(str(int(y[i])),(x[i],y[i])) 

Gives me IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices and if i do astype(int) i get IndexError: index 8 is out of bounds for axis 0 with size 7 which I don't understand as I'm indexing from 0 to -1?

Can you help me with what I am trying to do and add something that limits it to only run plt.annotate for x values in the range of xlim? Thanks a lot

Data:

x = [ 1.5293  2.9786  8.6734 11.944  13.309  13.337  14.591 ]
y = [  3978.072   1391.799   1739.091 218146.734  29643.477  29680.311
    965.577]
xlim = [11.5, 12.5]

CodePudding user response:

As said in comments, you are directly iterating over the values of x and y, so no need to index:

import numpy as np
import matplotlib.pyplot as plt

x = [1.5293, 2.9786, 8.6734, 11.944, 13.309, 13.337, 14.591]
y = [3978.072, 1391.799, 1739.091, 218146.734, 29643.477, 29680.311, 965.577]
xlim = [11.5, 12.5]

fig, ax = plt.subplots()

ax.plot(x, y, "-o")
for x_, y_ in zip(x, y):
    if xlim[0] < x_ < xlim[1]:
        ax.annotate(str(y_), (x_, y_))

plt.show()

annotated figure

  • Related