This repository has been archived on 2021-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
scientificComputing/statistics/lecture/cumulative.py

53 lines
1.5 KiB
Python

import numpy as np
import matplotlib.pyplot as plt
# data:
rng = np.random.RandomState(981)
data = rng.randn(100)
xs = np.sort(data)
cdf = np.arange(len(xs))/float(len(xs))
# Gauss:
dx = 0.01
xx = np.arange(-4.0, 4.0, dx)
gauss = np.exp(-0.5*xx*xx)/np.sqrt(2.0*np.pi)
gausscdf = np.cumsum(gauss)*dx
# plot:
plt.xkcd()
fig = plt.figure( figsize=(6, 2.6) )
ax = fig.add_subplot(1, 1, 1)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.set_xlabel( 'x' )
ax.set_xlim(-3.2, 3.2)
ax.set_xticks( np.arange( -3.0, 3.1, 1.0 ) )
ax.set_ylabel( 'F(x)' )
ax.set_ylim(-0.05, 1.05)
ax.set_yticks( np.arange( 0.0, 1.1, 0.2 ) )
med = xs[cdf>=0.5][0]
ax.plot([-3.2, med, med], [0.5, 0.5, 0.0], 'k', lw=1, zorder=-5)
ax.text(-2.8, 0.55, 'F=0.5')
ax.text(0.15, 0.25, 'median at %.2f' % med)
q3 = xs[cdf>=0.75][0]
ax.plot([-3.2, q3, q3], [0.75, 0.75, 0.0], 'k', lw=1, zorder=-5)
ax.text(-2.8, 0.8, 'F=0.75')
ax.text(0.8, 0.5, '3. quartile at %.2f' % q3)
p = cdf[xs>=-1.0][0]
ax.plot([-3.2, -1.0, -1.0], [p, p, 0.0], 'k', lw=1, zorder=-5)
ax.text(-2.8, 0.2, 'F=%.2f' % p)
ax.text(-0.9, 0.05, '-1')
ax.plot(xx, gausscdf, '-', color='#0000ff', lw=2, zorder=-1)
ax.plot(xs, cdf, '-', color='#cc0000', lw=4, zorder=-1)
ax.plot([-3.2, 3.2], [1.0, 1.0], '--', color='k', lw=2, zorder=-10)
plt.subplots_adjust(left=0.1, right=0.98, bottom=0.15, top=0.98, wspace=0.35, hspace=0.3)
fig.savefig( 'cumulative.pdf' )
#plt.show()