简体   繁体   中英

on_click/hover event for bqplot image

I'm trying to build an interactive dashboard using ipywidgets and bqplot with image chips and a scatterplot. Each point in the scatterplot corresponds to an image chip, and so I would like (1) to 'highlight' the point when hovering over the corresponding image, and (2) change the color of the point and storing the x value when clicking in an image.

Although the on_click and on_hover exist for the Image mark, I did not manage to make them work. See below what I have so far

import io
import datetime

import numpy as np
import ipywidgets as ipw
from PIL import Image as PImage
import bqplot as bqp
import pandas as pd

#########
## Generate list of random images, with associated x and y values
#########
def random_image():
    """Generate a random ipywidget Image
    """
    arr = np.random.randint(255, size=(300, 300, 3), dtype=np.uint8)
    img = PImage.fromarray(arr)
    with io.BytesIO() as fileobj:
        img.save(fileobj, 'PNG')
        img_b = fileobj.getvalue()
    img_w = ipw.Image(value=img_b)
    return img_w


origin = datetime.datetime(2020, 1, 1)
img_list = [{'image': random_image(),
             'x': origin + datetime.timedelta(idx),
             'y': np.sin(idx)} for idx in range(10)]

###########
## Create scatter plot
###########
scale_y = bqp.LinearScale()
scale_x = bqp.DateScale()
scatter = bqp.Scatter(x=pd.Series([item['x'] for item in img_list]),
                      y=[item['y'] for item in img_list],
                      scales={'x': scale_x, 'y': scale_y})
axis_x = bqp.Axis(scale=scale_x)
axis_y = bqp.Axis(scale=scale_y, orientation='vertical')

scat_fig = bqp.Figure(marks=[scatter],
                      layout={'width':'1500px', 'height':'300px'},
                      axes=[axis_x, axis_y])


#########
## Create grid (or row) of image chips
#########
layout = ipw.Layout(width='150px', height='200px')
img_fig_list = []
for item in img_list:
    image = bqp.Image(image=item['image'])
    fig = bqp.Figure(
#         title=item['x'].strftime('%Y-%m-%d'),
        marks=[image], padding_x=0, padding_y=0, min_aspect_ratio=1, max_aspect_ratio=1,
        fig_margin = dict(top=10, bottom=10, left=10, right=10),
        layout=layout)
    #image.on_click(click_fn)
    img_fig_list.append(fig)

############
## Combine scatter and image chips and display them
############
img_row = ipw.HBox(img_fig_list)
ipw.VBox([scat_fig, img_row])

Bonus question: Is it possible to have multiple images side by side within the same figure?

on_hover() will work, just define a callback function so the it is called when you hover. Try using on_element_click() instead of on_click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM