Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the x value corresponding to a histogram max

I re-worded this to confirm to the idea of S.O. (thanks Michael0x2a)

I have been trying to find the x value associated with the maximum of a histogram plotted in matplotlib.pyplot. At first I had trouble even finding out how to access the data of the histogram just using the code

import matplotlib.pyplot as plt

# Dealing with sub figures...
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(<your data>, bins=<num of bins>, normed=True, fc='k', alpha=0.3)

plt.show()

Then after doing some reading online (and around these forums) I found that you can 'extract' the histogram data like so:

n, bins, patches = ax.hist(<your data>, bins=<num of bins>, normed=True, fc='k', alpha=0.3)

Basically I need to know how to find the value of bins that the maximum n corresponds to!

Cheers!

like image 775
FriskyGrub Avatar asked Sep 16 '13 00:09

FriskyGrub


1 Answers

You can also do this with a numpy function.

elem = np.argmax(n)

Which will be much faster than a python loop (doc).

If you do want to write this as a loop, I would write it as such

nmax = np.max(n)
arg_max = None
for j, _n in enumerate(n):
    if _n == nmax:
        arg_max = j
        break
print b[arg_max]
like image 115
tacaswell Avatar answered Sep 28 '22 00:09

tacaswell