【问题标题】:How to get x -coordinates and y- coordinates on tap in bokeh如何在散景中点击获取 x 坐标和 y 坐标
【发布时间】:2019-05-27 10:54:44
【问题描述】:

我遇到了如何使用 Tap 工具在散景图中显示 x 和 y 坐标的问题

我尝试了以下代码。现在我想为点击工具写一个回调,我该怎么做。如何在单击正方形时显示 x 和 y 坐标

  from bokeh.models import ColumnDataSource, OpenURL, TapTool
  from bokeh.plotting import figure, output_file, show

  output_file("openurl.html")

  p = figure(plot_width=400, plot_height=400,
               tools="tap", title="Click the Dots")

  source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2, 
                         7]))


  p.square('x', 'y', color='green', size=20, source=source)

  taptool = p.select(type=TapTool)

  show(p)

【问题讨论】:

    标签: python callback bokeh tap


    【解决方案1】:

    您可以通过编写在选择更改时调用的回调来获取点击时的 x 和 y 坐标。当前选定字形的索引可以在 source.selected.indices 中找到。这些索引可用于从 source.data 中获取 x 和 y 坐标。这段代码在浏览器的控制台中打印 x 和 y 坐标 (F12)。

    from bokeh.models import ColumnDataSource, TapTool, CustomJS
    from bokeh.plotting import figure, output_file, show
    
    output_file("openurl.html")
    
    p = figure(plot_width=400, plot_height=400,
                 tools="tap", title="Click the Dots")
    
    source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[2, 5, 8, 2, 7]))
    
    p.square('x', 'y', color='green', size=20, source=source)
    
    callback = CustomJS(args=dict(source=source), code="""
        var selectedIndex = source.selected.indices;
        for (var i = 0; i < selectedIndex.length; i++) {
            console.log("Index:", selectedIndex[i]);
            console.log("x:", source.data['x'][selectedIndex[i]]);
            console.log("y:", source.data['y'][selectedIndex[i]]);
        }
    """)
    
    taptool = p.select(type=TapTool)
    source.selected.js_on_change('indices', callback)
    show(p)
    

    【讨论】:

    • 我收到以下错误我该如何解决:AttributeError: 'PropertyValueDict' object has no attribute 'js_on_change'
    • 您使用的是哪个版本的 Bokeh?
    • 作为参考,js_on_change 是两年半前添加的,在 0.12.4 如果版本真的那么古老,我的第一个建议是升级。如果这是不可能的,那么唯一的选择是使用源本身的旧样式.callback 属性,如此处所示bokeh.pydata.org/en/0.12.3/docs/user_guide/interaction/…
    • @Jasper 使用 Bokeh 版本 0.12.4
    • 这就是问题所在。请按照 bigreddot 的建议升级或使用旧文档。
    猜你喜欢
    • 2014-12-02
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2015-05-23
    相关资源
    最近更新 更多