【问题标题】:How to retrieve coordinates of PointDrawTool in Bokeh?如何在 Bokeh 中检索 PointDrawTool 的坐标?
【发布时间】:2020-07-10 11:29:49
【问题描述】:

我正在尝试获取用户绘制的点的 xy 坐标。我想将它们作为字典、列表或 pandas DataFrame。

我在 Jupyter 中使用 Bokeh 2.0.2。会有一个背景图片(这不是本文的重点),在顶部,用户将创建我可以进一步使用的点。

下面是我设法到达的地方(带有一些虚拟数据)。我已经评论了一些我认为是我必须走的方向的行。但我似乎没有掌握它。

from bokeh.plotting import figure, show, Column, output_notebook
from bokeh.models import PointDrawTool, ColumnDataSource, TableColumn, DataTable
output_notebook()
my_tools = ["pan, wheel_zoom, box_zoom, reset"]

#create the figure object
p = figure(title= "my_title", match_aspect=True,
           toolbar_location = 'above', tools = my_tools)

seeds = ColumnDataSource({'x': [2,14,8], 'y': [-1,5,7]}) #dummy data
renderer = p.scatter(x='x', y='y', source = seeds, color='red', size=10)
columns = [TableColumn(field="x", title="x"),
           TableColumn(field="y", title="y")]

table = DataTable(source=seeds, columns=columns, editable=True, height=100)

#callback = CustomJS(args=dict(source=seeds), code="""
#    var data = source.data;
#    var x = data['x']
#    var y = data['y']
#    source.change.emit();
#""")
#
#seeds.x.js_on_change('change:x', callback)

draw_tool = PointDrawTool(renderers=[renderer])
p.add_tools(draw_tool)
p.toolbar.active_tap = draw_tool

show(Column(p, table))

【问题讨论】:

    标签: python pandas callback bokeh


    【解决方案1】:

    来自https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#pointdrawtool的文档:

    该工具会根据字形的 x 和 y 值自动修改数据源上的列。添加新点时,数据源中的任何其他列都将使用声明的 empty_value 填充。任何新添加的点都将插入到第一个提供的渲染器的 ColumnDataSource 上。

    所以,只需检查相应的数据源,seeds 就在您的情况下。

    这里唯一的问题是您是否想确切地知道已更改或添加的点。在这种情况下,最简单的解决方案是创建一个自定义的 PointDrawTool 子类来实现这一点。或者,您可以创建一个额外的“原始”数据源,并在每次更新时将其与 seeds 进行比较。

    【讨论】:

    • 谢谢尤金!我确实阅读了文档,我认为上述内容也可以。不幸的是,当我查看seeds.data 时,我仍然只得到初始输入{'x': [2, 14, 8], 'y': [-1, 5, 7]},但没有新输入。
    • “当我看seeds.data” - 但你什么时候看?在 CustomJS 回调中?
    • seeds.js_on_change('data', CustomJS(code="console.log(cb_obj.data);"))添加到您的代码中,您将在JS控制台中看到打印出来的更新数据。
    • 嗨尤金,很抱歉我的沟通不太清楚。当我说“我查看 seeds.data”时,我的意思是在另一个 Jupyther 单元中,我执行 seeds.data 来检查种子中包含的内容,并且只获取原始输入。
    • 我总是看到更新后的表格打印在我的图表下方。尽管我设法将您推荐的 sn-p 包括在内,但似乎没有任何改变。我仍然可以在调用seeds 时看到原始单元格输出的更新表,但我仍然只得到原始输入,而不是使用draw_tool 绘制的新点的坐标
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    相关资源
    最近更新 更多