Plotly (offline) for Python click events

余生长醉 提交于 2019-12-25 03:56:11

问题


I need to get click events in Plotly (offline) in Jupyter.

The way I am thinking to handle this is use javascript and the following command to return the values to python:

var kernel = IPython.notebook.kernel;
kernel.execute(command);

...where command would be something like variable = xxxxx (just like here)

I am stucked in the beggining of my attempt, trying to plot a chart in HTML in python (observe that I can succesfully load jQuery this way):

from IPython.display import HTML
HTML('''
    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        </head>
        <body>
            <h3>Gráfico</h3>
            <hr>
            <div id="myDiv"></div>
            <script>

                var trace1 = {
                  x: [1, 2, 3, 4],
                  y: [10, 15, 13, 17],
                  mode: 'markers'
                };

                var trace2 = {
                  x: [2, 3, 4, 5],
                  y: [16, 5, 11, 10],
                  mode: 'lines'
                };

                var trace3 = {
                  x: [1, 2, 3, 4],
                  y: [12, 9, 15, 12],
                  mode: 'lines+markers'
                };

                var data = [ trace1, trace2, trace3 ];
                var layout = {};
                Plotly.newPlot('myDiv', data, layout);
            </script>
        </body>
    </html>
''')

The error message is:

ReferenceError: Plotly is not defined at eval (eval at globalEval (jquery.min.js:2), :21:17) at eval () at Function.globalEval (jquery.min.js:2) at ua (jquery.min.js:3) at n.fn.init.append (jquery.min.js:3) at OutputArea._safe_append (outputarea.js:456) at OutputArea.append_execute_result (outputarea.js:493) at OutputArea.append_output (outputarea.js:326) at OutputArea.handle_output (outputarea.js:257) at output (codecell.js:382)


回答1:


I have managed to get clicked points from this answer

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
from plotly import tools
import pandas as pd
import numpy as np
from datetime import datetime
init_notebook_mode(connected=True)
from IPython.core.display import display, HTML


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

Chosen = []

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

data = [trace]

# Plot and embed in ipython notebook!
plot = plot(data, filename='basic-scatter', include_plotlyjs=False, output_type='div')
divId=plot.split("id=\"",1)[1].split('"',1)[0]
plot = plot.replace("Plotly.newPlot", "var graph = Plotly.newPlot")
plot = plot.replace("</script>", """
var graph = document.getElementById('"""+divId+"""');
var color1 = '#7b3294';
var color1Light = '#c2a5cf';
var colorX = '#ffa7b5';
var colorY = '#fdae61';
var kernel = IPython.notebook.kernel;
;graph.on('plotly_selected', function(eventData) {
  var x = [];
  var y = [];

  var colors = [];
  for(var i = 0; i < %i; i++) colors.push(color1Light);

  eventData.points.forEach(function(pt) {
    x.push(pt.x);
    y.push(pt.y);
    colors[pt.pointNumber] = color1;
    var comando = 'Chosen.append((' + pt.x + ', ' + pt.y + '))'
    console.log(comando);
    kernel.execute(comando);

  });


  Plotly.restyle(graph, 'marker.color', [colors], [0]);
});
""" % N)
display(HTML(plot))

In this example we are able to make a two-way communication between Javascript and Python. Observe that the data that creates the chart comes from Python. After points are chosen, I append a tuple to Chosen variable, which belongs to Pythhon scope.



来源:https://stackoverflow.com/questions/52107955/plotly-offline-for-python-click-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!