Interactive plotting with bqplot and ipywidgets

https://github.com/bloomberg/bqplot

https://github.com/bloomberg/bqplot/tree/master/examples

https://github.com/jupyter-widgets/ipywidgets/blob/master/docs/source/examples/Image%20Browser.ipynb

Need to enable ipywidgets with

jupyter nbextension enable --py widgetsnbextension

In [1]:
import matplotlib.pyplot as plt
import numpy as np
import string
import random

# nbagg is needed for drawing over an existing figure 
# (seems that it will be available elsewhere with matplotlib 2.1)
%matplotlib nbagg

In [2]:
from bqplot import LinearScale
from bqplot import Scatter
from bqplot import Axis, Figure
from bqplot import Tooltip

In [3]:
import ipywidgets

In [4]:
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def toy_data(num_examples=30):
    """Simulate some 2D data"""
    random.seed(1234)
    np.random.seed(1234)
    data = np.random.rand(num_examples, 2)
    names = []
    for ix in range(num_examples):
        names.append(id_generator())
    
    return names, data

In [5]:
names, data = toy_data()

In [6]:
# We need to create a figure first before passing it to ipywidgets.

fig = plt.figure(figsize=(3,3))
ax = fig.add_subplot(111)



In [7]:
def browse_images(names, fig):
    def get_image(name, fig):
        """Simulate returning an image for a given name"""
        fig.clear()
        ax.plot([0, 1], [1, 0], 'ro')
        fig.text(0.2, 0.5, name)
    ipywidgets.interact(get_image, name=names, fig=ipywidgets.fixed(fig))

In [8]:
browse_images(names, fig)



In [9]:
def print_event(self, target):
    print(target)

def draw_event(self, target):
    print(target)
    browse_images((target['data']['name']), fig)
    
def_tt = Tooltip(fields=['name', 'x', 'y'], formats=['', '.3f', '.2f'])

In [10]:
lin_scale = LinearScale()
results = Scatter(x=data[:,0], y=data[:,1], names=names, display_names=False,
                  scales={'x': lin_scale, 'y': lin_scale},
                  name='Money shot', default_opacities=[0.6],
                  interactions={'hover': 'tooltip', 'click': 'select'},
                  selected_style={'opacity': 1.0, 'fill': 'DarkOrange', 'stroke': 'Red'},
                  unselected_style={'fill': 'Blue'})

results.on_background_click(print_event)
results.on_element_click(draw_event)
results.tooltip = def_tt

In [11]:
ax_x = Axis(scale=lin_scale, grid_lines='solid', label='X')
ax_y = Axis(scale=lin_scale, orientation='vertical', grid_lines='dashed', label='Y')

# details = TwoDSelector(x_scale=lin_scale, y_scale=lin_scale)
scatter_fig = Figure(marks=[results], axes=[ax_x, ax_y], title='Very cool interaction')

In [12]:
scatter_fig

# Look at the figure above!


{'event': 'element_click', 'data': {'index': 5, 'name': 'R9ET4W', 'unique_id': 'R9ET4W', 'y': 0.5009951255234587, 'x': 0.35781726995786667}}

In [ ]:


In [ ]: