我下面有创建简单的x-y线图的代码。
我希望能够交互式地测量图中各点之间的距离,并最好将其显示在图形上,但在附近的字形中也可以。
说我使用某种工具从一个点单击并拖动到另一点(或地图上的随机点),我想要一些东西来告诉我以x为单位的距离(在此示例中,实际上不需要y或欧氏距离)。
我该怎么做?
from bokeh.io import output_file, show, save
from bokeh.layouts import column
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
data = []
x = list(range(11))
y0 = x
y1 = [10 - xx for xx in x]
y2 = [abs(xx - 5) for xx in x]
source = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1, y2=y2))
for i in range(3):
p = figure(title="Title "+str(i), plot_width=300, plot_height=300)
if len(data):
p.x_range = data[0].x_range
p.y_range = data[0].y_range
p.circle('x', 'y0', size=10, color="navy", alpha=0.5, legend_label='line1', source=source)
# p.triangle('x', 'y1', size=10, color="firebrick", alpha=0.5, legend_label='line2', source=source)
# p.square('x', 'y2', size=10, color="olive", alpha=0.5, legend_label='line3', source=source)
p.legend.location = 'top_right'
p.legend.click_policy = "hide"
data.append(p)
plot_col = column(data)
# show the results
show(plot_col)
您可以使用TapTool和CustomJS回调来完成。我在您的代码中添加了一个代码,该代码仅记录了每个点的x值以及第一和第二选择之间的距离到JS控制台;您可以使用此信息更新附近字形的源。
from bokeh.io import output_file, show, save
from bokeh.layouts import column
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, CustomJS, TapTool
# output_file("panning.html")
data = []
x = list(range(11))
y0 = x
y1 = [10 - xx for xx in x]
y2 = [abs(xx - 5) for xx in x]
source = ColumnDataSource(data=dict(x=x, y0=y0, y1=y1, y2=y2))
x_list = []
for i in range(1):
callback = CustomJS(args=dict(source=source, x_list=x_list), code='''
var selected_x = source.data.x[source.selected.indices];
if (x_list.length == 0) // indicates that this is the first point selected
{
console.log("First point selected is "+selected_x)
x_list.push(selected_x);
}
else // this is the second point selected
{
console.log("Second point is " + selected_x + ". Distance is " + (selected_x - x_list[0]))
x_list.pop();
}
''')
p = figure(title="Basic Title", plot_width=800, plot_height=400)
p.add_tools(TapTool(callback=callback))
if len(data):
p.x_range = data[0].x_range
p.y_range = data[0].y_range
p.circle('x', 'y0', size=10, color="navy", alpha=0.5, legend_label='line1', source=source)
p.legend.location = 'top_right'
p.legend.click_policy = "hide"
data.append(p)
plot_col = column(data)
# show the results
show(plot_col)
#save(plot_col)