我需要在Jupyter的Plotly(离线)中获得点击事件。
我想处理此问题的方式是使用javascript和以下命令将值返回给python:
var kernel = IPython.notebook.kernel;
kernel.execute(command);
...其中的命令类似于variable = xxxxx
(就像here)
我陷入了尝试的开端,试图在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>
''')
错误消息是:
ReferenceError:未定义情节 在评估时(在globalEval评估时(jquery.min.js:2),:21:17) 于eval() 在Function.globalEval(jquery.min.js:2) 在UA(jquery.min.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)
答案 0 :(得分:0)
我设法从此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))
在此示例中,我们能够进行 Javascript和Python之间的双向通信。请注意,创建图表的数据来自Python。选择点后,我将一个元组附加到Chosen
变量中,该变量属于Pythhon范围。