import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt

# normal distribution:
x = np.arange( -3.0, 3.0, 0.01 )
g = np.exp(-0.5*x*x)/np.sqrt(2.0*np.pi)

plt.xkcd()
fig = plt.figure( figsize=(6,3) )
ax = fig.add_subplot(1, 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_ylabel( 'Prob. density p(x)' )
ax.set_ylim( 0.0, 0.46 )
ax.set_yticks( np.arange( 0.0, 0.45, 0.1 ) )
ax.text(-1.0, 0.06, '50%', ha='center' )
ax.text(+1.0, 0.06, '50%', ha='center' )
ax.annotate('Median\n= mean',
            xy=(0.1, 0.3), xycoords='data',
            xytext=(1.2, 0.35), textcoords='data', ha='left',
            arrowprops=dict(arrowstyle="->", relpos=(0.0,0.2),
            connectionstyle="angle3,angleA=10,angleB=40") )
ax.annotate('Mode',
            xy=(-0.1, 0.4), xycoords='data',
            xytext=(-2.5, 0.43), textcoords='data', ha='left',
            arrowprops=dict(arrowstyle="->", relpos=(0.0,0.2),
            connectionstyle="angle3,angleA=10,angleB=120") )
ax.fill_between( x[x<0], 0.0, g[x<0], color='#ffcc00' )
ax.fill_between( x[x>0], 0.0, g[x>0], color='#99ff00' )
ax.plot(x, g, 'b', lw=4)
ax.plot([0.0, 0.0], [0.0, 0.45], 'k', lw=2 )

# normal distribution:
x = np.arange( 0.0, 6.0, 0.01 )
shape = 2.0
g = st.gamma.pdf(x, shape)
m = st.gamma.median(shape)
gm = st.gamma.mean(shape)
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_ylabel( 'Prob. density p(x)' )
ax.set_ylim( 0.0, 0.46 )
ax.set_yticks( np.arange( 0.0, 0.45, 0.1 ) )
ax.text(m-0.8, 0.06, '50%', ha='center' )
ax.text(m+1.2, 0.06, '50%', ha='center' )
ax.annotate('Median',
            xy=(m+0.1, 0.2), xycoords='data',
            xytext=(m+1.6, 0.25), textcoords='data', ha='left',
            arrowprops=dict(arrowstyle="->", relpos=(0.0,0.5),
            connectionstyle="angle3,angleA=30,angleB=70") )
ax.annotate('Mean',
            xy=(gm, 0.01), xycoords='data',
            xytext=(gm+1.8, 0.15), textcoords='data', ha='left',
            arrowprops=dict(arrowstyle="->", relpos=(0.0,0.5),
            connectionstyle="angle3,angleA=0,angleB=90") )
ax.annotate('Mode',
            xy=(1.0, 0.38), xycoords='data',
            xytext=(1.8, 0.42), textcoords='data', ha='left',
            arrowprops=dict(arrowstyle="->", relpos=(0.0,0.5),
            connectionstyle="angle3,angleA=0,angleB=70") )
ax.fill_between( x[x<m], 0.0, g[x<m], color='#ffcc00' )
ax.fill_between( x[x>m], 0.0, g[x>m], color='#99ff00' )
ax.plot(x, g, 'b', lw=4)
ax.plot([m, m], [0.0, 0.38], 'k', lw=2 )
#ax.plot([gm, gm], [0.0, 0.42], 'k', lw=2 )

plt.tight_layout()
fig.savefig( 'median.pdf' )
#plt.show()
