Question

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.

Was it helpful?

Solution

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]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top