我需要在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:Plotly未定义在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)在OutputArea.append_output(outputaa.aps)上的OutputArea.append_execute_result(outputarea.js:493)的OutputArea._safe_append(outputarea.js:456)的n.fn.init.append(jquery.min.js:3)处输出.js:326)输出处的OutputArea.handle_output(outputarea.js:257)(codecell.js:382)
我已经设法从这个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范围。