【问题标题】:Plotly (offline) for Python click eventsPlotly(离线)用于 Python 点击​​事件
【发布时间】:2018-08-31 03:12:55
【问题描述】:

我需要在 Jupyter 的 Plotly(离线)中获取点击事件。

我想处理这个问题的方法是使用 javascript 和以下命令将值返回给 python:

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

...where 命令类似于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 (在 globalEval 的 eval (jquery.min.js:2), :21:17) 在评估() 在 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)

【问题讨论】:

    标签: python jupyter-notebook


    【解决方案1】:

    我已经设法从这个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 范围。

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多