In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from ipywidgets import interact, widgets
from IPython.display import display, clear_output
In [2]:
sns.set_context('paper')
sns.set_style('ticks')
In [3]:
def draw_sample(weights):
choice = np.random.uniform(0, sum(weights))
cum_weight = 0
choiceIdx = 0
for weight in weights:
#choice -= weight
cum_weight += weight
if choice <= cum_weight:
break
choiceIdx += 1
return choiceIdx, choice
list(draw_sample([1,2,3,4]) for i in xrange(10))
Out[3]:
In [ ]:
weights = [1,2,3,4]
x = np.cumsum([0] + weights)
y = np.ones_like(x)
fig, ax = plt.subplots(1,1, figsize=(10,2))
ax.plot(x, y, lw=50, alpha=0.5)
ax.plot(x[1:], y[1:], linestyle='none',
marker='|', ms=100,
markeredgecolor='k', mew=1,
color='k')
ax.set_xlim(0, x.max())
choiceIdx, choice = draw_sample(weights)
ax.plot(choice, 1, linestyle='none',
marker='|', ms=50,
markeredgecolor='r', mew=5,
color='r', label='sample')
ax.set_title('Draw=%s' % choiceIdx)
plt.axis('off')
Out[ ]:
In [ ]:
def draw_interact(weights):
clear_output(wait=True)
weights = weights
x = np.cumsum([0] + weights)
y = np.ones_like(x)
fig, ax = plt.subplots(1,1, figsize=(10,2))
ax.plot(x, y, lw=50, alpha=0.5)
ax.plot(x[1:], y[1:], linestyle='none',
marker='|', ms=100,
markeredgecolor='k', mew=1,
color='k')
ax.set_xlim(0, x.max())
choiceIdx, choice = draw_sample(weights)
ax.plot(choice, 1, linestyle='none',
marker='|', ms=50,
markeredgecolor='r', mew=5,
color='r', label='sample')
ax.set_title('Draw=%s' % choiceIdx)
plt.axis('off')
In [ ]:
button = widgets.Button(description="Sample")
display(button)
button.on_click(lambda x: draw_interact([1,2,3,4]))
In [ ]: