FriskyGrub
FriskyGrub

Reputation: 1049

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!

Upvotes: 5

Views: 28656

Answers (3)

Guest
Guest

Reputation: 71

import matplotlib.pyplot as plt
import numpy as np
import pylab as P

mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)

n, b, patches = plt.hist(x, 50, normed=1, histtype='stepfilled')

bin_max = np.where(n == n.max())

print 'maxbin', b[bin_max][0]

Upvotes: 7

FriskyGrub
FriskyGrub

Reputation: 1049

This can be achieved with a simple 'find-n-match' sort of approach

import matplotlib.pyplot as plt

# Yur sub-figure stuff
fig = plt.figure()
ax = fig.add_subplot(111)
n,b,p=ax.hist(<your data>, bins=<num of bins>)

# Finding your point
for y in range(0,len(n)):
    elem = n[y]
    if elem == n.max():
     break
else:   # ideally this should never be tripped
    y = none
print b[y] 

so b is the 'x values' list, b[y] is the 'x value' corresponding to n.max() Hope that helps!

Upvotes: 0

tacaswell
tacaswell

Reputation: 87376

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]

Upvotes: 7

Related Questions