简体   繁体   中英

How to make an interactive bokeh plot?

I am trying bokeh for the first time to make an interactive plot on a web browser. I plot some circles, and want some interaction (callback) when I click on one of the circles. I have followed the example given here , but I am failing badly...

When starting the script with bokeh serve --show test.py I see the plot with the five circles, but when clicking on any circle,I neither see any print-output on the command console nor the sixth circle drawn.

Expected behaviour: I see five circles, and when I click on one of them I expect to have a printout ("test") and added the sixth circle (at coordinates 60/60).

Maybe its the wrong tool altogether? Anyway, here is the complete code ( test.py ):

from random import random

from bokeh.layouts import column
from bokeh.models import Button, TapTool
from bokeh.palettes import RdYlBu3
from bokeh.plotting import figure, curdoc

# create a plot and style its properties
p = figure(x_range=(0, 100), y_range=(0, 100), toolbar_location=None)
p.border_fill_color = 'black'
p.background_fill_color = 'black'
p.outline_line_color = None
p.grid.grid_line_color = None
p.circle([10, 20, 30, 40, 50], [60, 70, 20, 40, 50], size=20, color="navy", alpha=0.5)

def foo():
    print("test")
    p.circle([60], [60], size=20, color="navy", alpha=0.5)


taptool = p.select(type=TapTool)
taptool.callback = foo

# # put the button and plot in a layout and add to the document
curdoc().add_root(column(p))

PS: I want to be able to click on the circles, get their coordinates, and draw lines dynamically between two circles I click on one after another.

When you want to add/remove/modify plotted data, it's good to put your data in a ColumnDataSource object, which can have a callback.

from bokeh.layouts import column
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, curdoc

p = figure(x_range=[0,100],y_range=[0,100],tools='tap')

source = ColumnDataSource(data={'x':[10, 20, 30, 40, 50],'y':[60, 70, 20, 40, 50]})

p.circle(x='x',y='y',size=20,source=source)

def foo(attr,old,new):
    new_source_data = {'x':source.data['x']+[60],'y':source.data['y']+[60]}
    source.data.update(new_source_data)

source.on_change('selected',foo)

curdoc().add_root(column(p))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM