2

I am looking to plot the relative frequency of a bunch of numbers in Python. I need to use the hist function, I have looked elsewhere on this site but I haven't found anything.

I am doing the following

x = array ([6.36,6.34,6.36,6.73,7.36,6.73])
hist (x)

When I do this I get a plot of just frequency, how do I make it relative frequency?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
user1778543
  • 167
  • 2
  • 9
  • 3
    Are you using [matplotlib](http://matplotlib.org/)? If not, what library are you using, since this is not in standard python? – NullUserException Oct 28 '12 at 16:46
  • Is it not the answer for your problem ? http://stackoverflow.com/questions/9767241/setting-a-relative-frequency-in-a-matplotlib-histogram – Darek Oct 28 '12 at 16:52
  • I am using matplotlib.pyplot I looked at that question before and tried using normed=1 but I still didn't get it I tried doing hist(x/x.sum()) but that reduce the values of the numbers in the x axis and does not change their frequency, so the y-axis is unchanged Thanks for the suggestions though – user1778543 Oct 28 '12 at 17:04
  • Any others suggestions @larsmans – user1778543 Oct 28 '12 at 18:58
  • Did you ever get this sorted out? – tacaswell Oct 05 '13 at 00:44

1 Answers1

3
hist(x, density=True)

The keyword density will plot the data such that the integral is 1 (doc). For old versions of Matplotlib you will need to use normed instead.

If you want the sum (not the integral) to be one

x = randn(30)
count,bins = np.histogram(x)
bar(bins[:-1],count,width = np.mean(np.diff(bins)))
tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • `normed` is deprecated. You can use `density` instead. It makes the integral (NOT the sum) equal 1. – root May 23 '18 at 18:34
  • @root Thanks for the comment! Answer updated accordingly. – tacaswell May 24 '18 at 16:48
  • 2
    Silly question: what's the difference between having the integral equal to 1 vs. the sum being 1? – neither-nor Dec 04 '18 at 22:24
  • 1
    @neither-nor Integral is the sum of the area under each bin (height times bin_width), so they are only equal if your bins are width 1. – eric Nov 24 '20 at 17:31
  • In case of sum to be one, I use `bar(bins[:-1],count/sum(count))`. I don't know but width argument seems to define the apparent width of the bars. https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html – masaya Jun 21 '22 at 10:45