|
| 1 | +# update a distribution based on new data. |
| 2 | +import numpy as np |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import scipy.stats as ss |
| 5 | +from matplotlib.animation import FuncAnimation |
| 6 | + |
| 7 | +class UpdateDist(object): |
| 8 | + def __init__(self, ax, prob=0.5): |
| 9 | + self.success = 0 |
| 10 | + self.prob = prob |
| 11 | + self.line, = ax.plot([], [], 'k-') |
| 12 | + self.x = np.linspace(0, 1, 200) |
| 13 | + self.ax = ax |
| 14 | + |
| 15 | + # Set up plot parameters |
| 16 | + self.ax.set_xlim(0, 1) |
| 17 | + self.ax.set_ylim(0, 15) |
| 18 | + self.ax.grid(True) |
| 19 | + |
| 20 | + # This vertical line represents the theoretical value, to |
| 21 | + # which the plotted distribution should converge. |
| 22 | + self.ax.axvline(prob, linestyle='--', color='black') |
| 23 | + |
| 24 | + def init(self): |
| 25 | + self.success = 0 |
| 26 | + self.line.set_data([], []) |
| 27 | + return self.line, |
| 28 | + |
| 29 | + def __call__(self, i): |
| 30 | + # This way the plot can continuously run and we just keep |
| 31 | + # watching new realizations of the process |
| 32 | + if i == 0: |
| 33 | + return self.init() |
| 34 | + |
| 35 | + # Choose success based on exceed a threshold with a uniform pick |
| 36 | + if np.random.rand(1,) < self.prob: |
| 37 | + self.success += 1 |
| 38 | + y = ss.beta.pdf(self.x, self.success + 1, (i - self.success) + 1) |
| 39 | + self.line.set_data(self.x, y) |
| 40 | + return self.line, |
| 41 | + |
| 42 | +fig = plt.figure() |
| 43 | +ax = fig.add_subplot(1, 1, 1) |
| 44 | +ud = UpdateDist(ax, prob=0.7) |
| 45 | +anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init, |
| 46 | + interval=100, blit=True) |
0 commit comments