"""
compute the mean and stddev of 100 data sets and plot mean vs stddev.
When you click on one of the mu, sigma points, plot the raw data from
the dataset that generated the mean and stddev
"""
import numpy
from pylab import figure, show


X = numpy.random.rand(100, 200)
xs = numpy.mean(X, axis=1)
ys = numpy.std(X, axis=1)

fig = figure()
ax = fig.add_subplot(211)
ax.set_title('click on point to plot time series')
line, = ax.plot(xs, ys, 'o', picker=5)  # 5 points tolerance
ax2 = fig.add_subplot(212)

def onpick(event):

    if event.artist!=line: return True

    N = len(event.ind)
    if not N: return True

    # the click locations
    x = event.mouseevent.xdata
    y = event.mouseevent.ydata
    
    
    distances = numpy.array(numpy.sqrt((x-xs[event.ind])**2. + (y-ys[event.ind])**2))
    indmin = int(numpy.nonzero(distances.min()==distances)[0])
    dataind = event.ind[indmin]
    print event.ind, distances, indmin, dataind, X[dataind][:5]
    
    ax2.cla()
    ax2.plot(X[dataind])
    ax2.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f'%(xs[dataind], ys[dataind]),
            transform=ax2.transAxes, va='top')
    ax2.set_ylim(-0.5, 1.5)        
    fig.canvas.draw()

    return True

fig.canvas.mpl_connect('pick_event', onpick)

show()





