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


/home/entity/anaconda2/lib/python2.7/site-packages/matplotlib/font_manager.py:279: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

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]:
[(3, 8.801258851368585),
 (3, 9.661611127118212),
 (3, 6.377488693044986),
 (1, 1.0779019868204842),
 (2, 3.781806880901213),
 (3, 6.779037541964296),
 (0, 0.9000133276624389),
 (3, 8.038897096255775),
 (3, 9.591574730508583),
 (3, 7.105690999971533)]

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[ ]:
(0.0, 10.0, 0.94499999999999995, 1.0550000000000002)

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 [ ]: