I am relatively new to python. I have plotted a histogram (say P(r)) of Gaussian random numbers (r) using the code given below w开发者_Go百科here 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()
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.
精彩评论