1

Im making a density plot like this How to create a density plot in matplotlib? im going to make axvlines to few spot on the plot and my problem is that I need to know that what is the exact x value of the highest peak.

I can find it with a loop:

    density = gaussian_kde(data)
    aa = 0
    bb = 0
    for i in range(max value of data):
       if density(i)[0]>aa:
            aa = density(i)[0]
            bb = i

after this bb has the x value of the peak but the time to do this loop is too long. it takes about 25 seconds at the moment and in future the size of data will be bigger

I hope that this isn't duplicate but atleast I couldn't find asnwer to this problem.

Community
  • 1
  • 1
TheLaama
  • 307
  • 2
  • 4
  • 12
  • Just a few comments on this: `density = density = gaussian_kde(data)` is a weird assignment as you have density twice. Then, unless you're using Python 3, you should not use `range` for great numbers, better use `xrange` because it won't hold the entire list of numbers in memory. – Johannes P Jul 29 '13 at 12:19
  • oh yeah. that density=density =.. wasn't there – TheLaama Jul 29 '13 at 14:11

1 Answers1

7

You could use numpy.argmax:

ys = density(np.arange(9))
bb = np.argmax(ys)
aa = ys[bb]

This would compute the same values of aa and bb as the code you posted. However, this only finds the max among integer values of x. If you look at Justin Peel's graph you'll see that the peak density can occur at some non-integer x-value. So, to find a closer approximation to the peak density, use

xs = np.linspace(0,8,200)
ys = density(xs)
index = np.argmax(ys)
max_y = ys[index]
max_x = xs[index]
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Are there any ways to get the number of peaks not only the max one ? – Yasmin Jul 07 '15 at 17:38
  • Since stackoverflow's goal is to build a *searchable* archive of good questions matched with good answers, let's make this a new question. Or, before asking, look at http://stackoverflow.com/a/26309701/190597 or http://stackoverflow.com/a/9113227/190597, and adapt the 2D solution to 1D. – unutbu Jul 07 '15 at 17:43