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/kerneldensity.py
2017-11-27 10:26:03 +01:00

84 lines
2.5 KiB
Python

import numpy as np
import matplotlib.pyplot as plt
# normal distribution:
rng = np.random.RandomState(6281)
x = np.arange( -4.0, 4.0, 0.01 )
g = np.exp(-0.5*x*x)/np.sqrt(2.0*np.pi)
r = rng.randn(100)
def kerneldensity(data, xmin, xmax, sigma=1.0) :
dx = 0.05*sigma
xg = np.arange(-4.0*sigma, 4.0*sigma + 0.5*dx, dx)
gauss = np.exp(-0.5*xg*xg/sigma/sigma)/np.sqrt(2.0*np.pi)/sigma
ng = len(gauss)//2
x = np.arange(xmin, xmax+0.5*dx, dx)
kd = np.zeros(len(x))
for xd in data:
inx = int((xd-xmin)/dx)
k0 = inx-ng
k1 = inx+ng+1
g0 = 0
g1 = len(gauss)
if inx < ng:
k0 = 0
g0 = ng-inx
if inx >= len(kd)-ng:
k1 = len(kd)
g1 = len(gauss)-(inx+ng-len(kd)+1)
kd[k0:k1] += gauss[g0:g1]
kd /= len(data)
return kd, x
plt.xkcd()
fig = plt.figure( figsize=(6,3) )
ax = fig.add_subplot(2, 2, 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( 'p(x)' )
ax.set_ylim(0.0, 0.49)
ax.set_yticks( np.arange( 0.0, 0.41, 0.1 ) )
#ax.plot(x, g, '-b', lw=2, zorder=-1)
ax.hist(r, np.arange(-4.1, 4, 0.4), normed=True, color='#FFCC00', zorder=-5)
ax = fig.add_subplot(2, 2, 3)
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( 'p(x)' )
ax.set_ylim(0.0, 0.49)
ax.set_yticks( np.arange( 0.0, 0.41, 0.1 ) )
#ax.plot(x, g, '-b', lw=2, zorder=-1)
ax.hist(r, np.arange(-4.3, 4, 0.4), normed=True, color='#FFCC00', zorder=-5)
ax = fig.add_subplot(1, 2, 2)
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( 'Probab. density p(x)' )
ax.set_ylim(0.0, 0.49)
ax.set_yticks( np.arange( 0.0, 0.41, 0.1 ) )
kd, xx = kerneldensity(r, -3.2, 3.2, 0.2)
ax.fill_between(xx, 0.0, kd, color='#FF9900', zorder=-5)
ax.plot(xx, kd, '-', lw=3, color='#CC0000', zorder=-1)
plt.subplots_adjust(left=0.1, right=0.98, bottom=0.15, top=0.98, wspace=0.35, hspace=0.3)
fig.savefig( 'kerneldensity.pdf' )
#plt.show()