简体   繁体   English

剧情(离线)Python单击事件

[英]Plotly (offline) for Python click events

I need to get click events in Plotly (offline) in Jupyter. 我需要在Jupyter的Plotly(脱机)中获得单击事件。

The way I am thinking to handle this is use javascript and the following command to return the values to python: 我想处理此问题的方式是使用javascript和以下命令将值返回给python:

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

...where command would be something like variable = xxxxx (just like here ) ...其中命令将类似于variable = xxxxx (就像这里

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): 我陷入尝试的开始,试图用python在HTML中绘制图表(注意,我可以通过这种方式成功加载jQuery):

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) ReferenceError:未在UA(jquery.min)的Function.globalEval(jquery.min.js:2)的eval()的eval()的eval(globalEval(jquery.min.js:2)、: 21:17)上定义Plotly .js:3)位于n.fn.init.append(jquery.min.js:3)在OutputArea._safe_append(outputarea.js:456)在OutputArea.append_execute_result(outputarea.js:493)在OutputArea.append_output(outputarea) .js:326)在OutputArea.handle_output(outputarea.js:257)在输出(codecell.js:382)

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 . 在此示例中,我们能够在Javascript和Python之间进行双向通信 Observe that the data that creates the chart comes from Python. 请注意,创建图表的数据来自Python。 After points are chosen, I append a tuple to Chosen variable, which belongs to Pythhon scope. 选择点之后,我将一个元组附加到Chosen变量中,该变量属于Pythhon范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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