[simulations] figure with normally distributed data
This commit is contained in:
47
simulations/lecture/normaldata.py
Normal file
47
simulations/lecture/normaldata.py
Normal file
@@ -0,0 +1,47 @@
|
||||
import numpy as np
|
||||
import scipy.stats as st
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.gridspec as gridspec
|
||||
from plotstyle import colors, cm_size, show_spines
|
||||
|
||||
if __name__ == "__main__":
|
||||
# wikipedia:
|
||||
# Generally, males vary in total length from 250 to 390 cm and
|
||||
# weigh between 90 and 306 kg
|
||||
n = 300
|
||||
mu = 200.0
|
||||
sigma = 50.0
|
||||
rng = np.random.RandomState(22281)
|
||||
indices = np.arange(n)
|
||||
data = 50.0*rng.randn(len(indices))+200.0
|
||||
|
||||
fig = plt.figure(figsize=cm_size(16.0, 8.0))
|
||||
spec = gridspec.GridSpec(nrows=1, ncols=2, width_ratios=[3, 1],
|
||||
left=0.12, bottom=0.17, right=0.97, top=0.98, wspace=0.08)
|
||||
ax1 = fig.add_subplot(spec[0, 0])
|
||||
show_spines(ax1, 'lb')
|
||||
ax1.scatter(indices, data, c=colors['blue'], edgecolor='white', s=50)
|
||||
ax1.set_xlabel('index')
|
||||
ax1.set_ylabel('Weight / kg')
|
||||
ax1.set_xlim(-10, 310)
|
||||
ax1.set_ylim(0, 350)
|
||||
ax1.set_yticks(np.arange(0, 351, 100))
|
||||
|
||||
ax2 = fig.add_subplot(spec[0, 1])
|
||||
show_spines(ax2, 'lb')
|
||||
xx = np.arange(0.0, 350.0, 0.5)
|
||||
yy = st.norm.pdf(xx, mu, sigma)
|
||||
ax2.plot(yy, xx, color=colors['red'])
|
||||
bw = 25.0
|
||||
h, b = np.histogram(data, np.arange(0, 351, bw))
|
||||
ax2.barh(b[:-1], h/np.sum(h)/(b[1]-b[0]), fc=colors['yellow'], height=0.9*bw, align='edge')
|
||||
ax2.set_xlabel('pdf / 1/kg')
|
||||
ax2.set_xlim(0, 0.01)
|
||||
ax2.set_xticks([0, 0.005, 0.01])
|
||||
ax2.set_xticklabels(['0', '0.005', '0.01'])
|
||||
ax2.set_ylim(0, 350)
|
||||
ax2.set_yticks(np.arange(0, 351, 100))
|
||||
ax2.set_yticklabels([])
|
||||
|
||||
fig.savefig("normaldata.pdf")
|
||||
plt.close()
|
||||
@@ -45,6 +45,16 @@ mean we just add the desired mean $\mu$ to the random numbers:
|
||||
x_i = \sigma \xi_i + \mu
|
||||
\end{equation}
|
||||
|
||||
\begin{figure}[t]
|
||||
\includegraphics[width=1\textwidth]{normaldata}
|
||||
\titlecaption{\label{normaldatafig} Generating normally distributed
|
||||
data.}{With the help of a computer the weight of 300 tigers can be
|
||||
measured in no time using the \code{randn()} function (left). We
|
||||
then even now the population distribution, its mean and standard
|
||||
deviation from which the simulated data values were drawn (red
|
||||
line, right).}
|
||||
\end{figure}
|
||||
|
||||
\begin{exercise}{normaldata.m}{normaldata.out}
|
||||
First, read the documentation of the \varcode{randn()} function and
|
||||
check its output for some (small) input arguments. Write a little
|
||||
|
||||
Reference in New Issue
Block a user