Skip to content

Instantly share code, notes, and snippets.

@geraintpalmer
Created January 6, 2016 10:50
Show Gist options
  • Save geraintpalmer/09a16e0211eace438550 to your computer and use it in GitHub Desktop.
Save geraintpalmer/09a16e0211eace438550 to your computer and use it in GitHub Desktop.
Updating Histogram with Matplotlib
from __future__ import division
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import random
import math
def lognormal_cdf(x, m, s):
x1 = x[0]
x2 = x[1]
inner1 = (math.log(x1) - m)/(s*math.sqrt(2))
inner2 = (math.log(x2) - m)/(s*math.sqrt(2))
cdf1 = 0.5 + 0.5*math.erf(inner1)
cdf2 = 0.5 + 0.5*math.erf(inner2)
return cdf2-cdf1
m = 1.5
s = 0.6
samplesize = 200
xlim = 20
ylim = 40
frac = 10
axticks = [(1/frac)*i for i in range(1, 30*frac + 1)]
axticks_shift1 = axticks[:-1]
axticks_shift2 = axticks[1:]
axticks_tuples = zip(axticks_shift1, axticks_shift2)
lognormdistplots = [lognormal_cdf(i, m, s)*(samplesize*frac) for i in axticks_tuples]
bins = range(31)
lognormrandoms = [random.lognormvariate(m, s) for i in range(samplesize)]
plt.ion()
fig = plt.figure()
ax = fig.gca()
plt.plot(axticks[1:], lognormdistplots, c='firebrick', linewidth=3)
plt.ylim([0, ylim])
plt.xlim([0, xlim])
plt.show()
# plt.savefig('giftest/img_1000')
wait = raw_input('Begin.')
for i in range(samplesize):
plt.cla()
plt.plot(axticks[1:], lognormdistplots, c='firebrick', linewidth=3)
ax.axvline(lognormrandoms[i], color='peru')
plt.hist(lognormrandoms[:i+1], bins=bins, color='goldenrod')
plt.ylim([0, ylim])
plt.xlim([0, xlim])
ax.text(15, 30, str(round(lognormrandoms[i], 3)), fontsize=20)
fig.canvas.draw()
# name = str(1) + str(0)*(3-len(str(i+1))) + str(i+1)
# plt.savefig('giftest/img_' + name)
plt.plot(axticks[1:], lognormdistplots, c='firebrick', linewidth=3)
plt.hist(lognormrandoms, bins=bins, color='goldenrod')
wait = raw_input('End.')
plt.show()
@drvinceknight
Copy link

Take a look at tqdm:

That's just two one line changes:

  • import tqdm
  • for i in tqdm.tqdm(range(samplesize)):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment