#!/usr/bin/python3 # script animated_Coin.py ''' example to produce random numbers (0/1) as obtained by throwing a coin animated fraction of heads vs. number of throws .. author:: Guenter Quast ''' # pyhton2 - python3 compatibility from __future__ import print_function, division, unicode_literals import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as anim import sys nthrow=499 # how often to throw #create a figure fig=plt.figure(figsize=(7.5,7.5)) ax=fig.add_subplot(1,1,1) ax.grid(True) ax.set_xlabel('N (number of trials)', size='x-large') ax.set_ylabel('p ($N_{head} / N$)', size='x-large') x=np.linspace(0.,nthrow,nthrow) # plot expectation ... ax.plot(x,0.5*np.ones(nthrow),'r--',lw=2) # ... and error band ax.plot(x,0.5+0.5/np.sqrt(x),'b--',lw=2) ax.plot(x,0.5-0.5/np.sqrt(x),'b--',lw=2) txt1 = ax.text(0.1, 0.9, ' ', transform=ax.transAxes,size='xx-large', bbox=dict(facecolor='silver', edgecolor='r', boxstyle='circle', pad=0.5)) txt2 = ax.text(0.81, 0.93, ' ', transform=ax.transAxes,size='x-large', backgroundcolor='white') # # throw the coin and plot N_head over (number of trials) Nh=0 N=0 def animate(i): global N,Nh, r, x N+=1 if np.random.rand()>0.5: Nh+=1 t=' O ' else: t='-1-' r=float(Nh)/float(N) # plot result graph, = ax.plot(float(N), r, 'g.') txt1.set_text(t) txt2.set_text('N = %i' %(N)) return graph, txt1,txt2 # # show as animated (=updating) graph print(('\n*==* script ' + sys.argv[0]+' executing')) ani=anim.FuncAnimation(fig, animate, nthrow, interval=20, blit=False, init_func=None, fargs=None, repeat=False) plt.show()