User interactions

Warning

The callbacks in the example will not work when view the documentation on readthedocs. The interactions require a Python kernel to work, so you should try this example locally.

Reacting to User Interaction in the Kernel

You can monitor user interactions, e.g. when a user clicks on a node, and have the kernel updated with the last interaction. See the cytoscape.js documentation for a full list of supported events you can listen for. We need to create a new graph before we can add interactivity:

[1]:
import ipycytoscape
[2]:
import json

# load the graph dictionary
with open("geneData.json") as fi:
    json_file = json.load(fi)

# load a style dictionary, which we'll use to update the graph's style
with open("geneStyle.json") as fi:
    s = json.load(fi)

# Create the cytoscape graph widget
cyto = ipycytoscape.CytoscapeWidget()
cyto.graph.add_graph_from_json(json_file)
cyto.set_style(s)
[3]:
# Display the graph.
cyto

Adding interactivity

Because we provided the monitor keyword argument, the client is already listening for user interactions and sending them to the kernel. We can listen for these events in the kernel and respond with some sort of callback. To do this, we call CytoscapeWidget.on with the type of event and widget we are listening for followed by a callback that takes as its only argument the JSON dictionary representation of the node or edge the user interacted with. Let’s create a simple example that prints the node’s ID and the type of interaction to an ipywidgets.Output widget:

[4]:
from ipywidgets import Output
from IPython.display import display
from pprint import pformat

out = Output()

def log_clicks(node):
    with out:
        print(f'clicked: {pformat(node)}')

def log_mouseovers(node):
    with out:
        print(f'mouseover: {pformat(node)}')

cyto.on('node', 'click', log_clicks)
cyto.on('node', 'mouseover', log_mouseovers)

Now display the graph again, this time with the (initially empty) log output below it, and try mousing over the nodes and clicking on them. You should see a stream of messages corresponding to your actions.

[5]:
# call `display` to show both widgets in one output cell
display(cyto)
display(out)
[ ]: