Wizard
Wizard

Reputation: 22113

Plot histogram of Benford law

I try to plot Benford's law

#+begin_src ipython :session alinbx :results none
from math import log10, log
import matplotlib
import matplotlib.pyplot as plt

matplotlib.rcParams['figure.figsize'] = (10.00, 6.18 )

def benford(n):
    return log10(n+1) - log10(n)

results = [benford(i) for i in range(1, 10)]
plt.plot(list(range(1,10)), results)
#+end_src

Run and get the result

enter image description here

The result I want is

enter image description here

Create histogram

#+begin_src ipython :session alinbx :results drawer
plt.hist(results,bins=9)
plt.axis([1, 10, 1])
#+end_src

but got the results

enter image description here

Then I spent hours reading:

I merely release that one should be super master at matplotlib before get this easy task done.

Could you please provide any hints?

Upvotes: 0

Views: 578

Answers (2)

The original plot that you show is a bar plot, not an histogram. Running your exact code with plt.bar(list(range(1,10)), results) instead of plt.hist(list(range(1,10)), results) results in: enter image description here

Upvotes: 1

Nathan
Nathan

Reputation: 3648

You want to plot a bar plot, not a histogram. You can do that as following:

import matplotlib.pyplot as plt
from math import log10


def benford(n):
    return log10(n+1) - log10(n)


x = [i for i in range(1, 10)]
results = [benford(i) for i in x]

fig, ax = plt.subplots()
plt.bar(x, results)
plt.xticks(x, x)
plt.show()

[1]: https://i.sstatic.net/LDOBd.png

Upvotes: 1

Related Questions