stpk
stpk

Reputation: 2125

Inject custom Javascript callbacks into my plot.ly code within a Jupyter Notebook

I'm using plotly to make charts inside my Jupyter Notebook (Python).

It works great, I did a lot of funky stuff, but I'm missing one thing - I want to run my custom JavaScript code when someone clicks on a datum in my 3D scatter plot (copy content into the clipboard). I'm basically missing a onclick parameter where I could pass some arbitrary JS code.

There is a tiny section on Click Events in the docs, but all the logic is implemented in JavaScript and it's not described how is it passed through.

How it looks in my dreams:

js_code = """ function myCallback( param ){...} """
trace = go.Scatter3d(
    x=x,
    y=y,
    z=z,
    mode='markers',
    customdata={"onclick": js_code}
)

In principal Plotly is a JavaScript library that just has Python API, so I'm sure it could execute my code if only I knew how to pass it through.

Upvotes: 2

Views: 1608

Answers (1)

ilmorez
ilmorez

Reputation: 328

There are few steps to get something similar to what you want:

  • get the HTML div from plotly
  • get the div id
  • use the id to add an event handler using Plotly JS
  • include Plotly JS

Here's the code:

import numpy as np
from IPython.core.display import display, HTML

N = 10
random_x = np.random.randn(N)
random_y = np.random.randn(N)

trace = go.Scatter(
    x = random_x,
    y = random_y,
    mode = 'markers'
)

data = [trace]

# get the a div
div = plot(data, include_plotlyjs=False, output_type='div')
# retrieve the div id (you probably want to do something smarter here with beautifulsoup)
div_id = div.split('=')[1].split()[0].replace("'", "").replace('"', '')
# your custom JS code
js = '''
    <script>
    var myDiv = document.getElementById('{div_id}');
    myDiv.on('plotly_click',
        function(eventdata) {{  
            alert('CLICK!');
        }}
    );
    </script>'''.format(div_id=div_id)
# merge everything
div = '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>' + div + js
# show the plot 
display(HTML(div))

Upvotes: 2

Related Questions