Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the bar heights of histogram P(x) corresponding to a given x?

Tags:

python

numpy

I am relatively new to python. I have plotted a histogram (say P(r)) of Gaussian random numbers (r) using the code given below where I have used the numpy.hist command. How can I now get the value of P(r) corresponding to a given value of r? I mean I need the bar height corresponding to a given value on the x-axis of the histogram. The code that I am using is the following:

import random 

sig=0.2 # width of the Gaussian

N=100000
nbins=100

R=[]
for i in range(100000):
    r=random.gauss(0,sig)
    R.append(r)
    i=i+1

import numpy as np
import matplotlib.pyplot as pl

pl.hist(R,nbins,normed=True)
pl.show()
like image 420
Sourabh Lahiri Avatar asked Feb 25 '23 06:02

Sourabh Lahiri


1 Answers

The hist() function returns the information you are looking for:

n, bins, patches = pl.hist(R, nbins, normed=True)

n is an array of the bar heights, and bins is the array of bin boundaries. In the given example, len(n) would be 100 and len(bins) would be 101.

Given some x value, you can use numpy.searchsorted() to find the index of the bin this value belongs to, and then use n[index] to extract the corresponding bar height.

like image 173
Sven Marnach Avatar answered Feb 26 '23 22:02

Sven Marnach