Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 761
stpk Avatar asked Mar 20 '26 22:03

stpk


1 Answers

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))
like image 106
ilmorez Avatar answered Mar 23 '26 12:03

ilmorez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!