I've spent the last few weeks learning the Bokeh package (which for visualizations, is excellent in my opinion).
Unfortunately, I have come across a problem that I can't for the life of me, figure out how to solve.
The below two links have been helpful, but I can't seem to replicate for my problem.
Using bokeh to plot interactive pie chart in Jupyter/Python - refer to answer #3
https://github.com/bokeh/bokeh/blob/0.12.9/examples/howto/notebook_comms/Jupyter%20Interactors.ipynb
The below code (in Jupyter) displays the graph correctly and displays the slider correctly, but I'm unsure how to connect the two as when I move the slider, the graph remains static.
I am using Python 3.6 and Bokeh 12.9
N = 300
source = ColumnDataSource(data={'x':random(N), 'y':random(N)})
plot = figure(plot_width=950, plot_height=400)
plot.circle(x='x', y='y', source=source)
callback = CustomJS(code="""
if (IPython.notebook.kernel !== undefined) {
var kernel = IPython.notebook.kernel;
cmd = "update_plot(" + cb_obj.value + ")";
kernel.execute(cmd, {}, {})};
""")
slider = Slider(start=100, end=1000, value=N, step=10, callback=callback)
def callback(attr, old, new):
N = slider.value
source.data={'x':random(N), 'y':random(N)}
slider.on_change('value', callback)
layout = column(slider, plot)
curdoc().add_root(layout)
show(widgetbox(slider, width = 300))
show(plot)
After reading the bokeh documentation and reading a view threads on GitHub, the 'callback' function is a little unclear for me as I'm not entirely sure what to parse to it (if in fact attr, old, new need certain elements parsed too it)
Any help would be greatly appreciated
Hopefully, I haven't missed anything glaringly obvious.
Kind Regards,
Adrian
You are currently mixing different ways for interactivity but unfortunately you always miss something for each different way.
The slider you use is from bokeh, but unfortunately it looks like slider.on_change only works if you run through the bokeh server. From the documentation:
Use bokeh serve to start the Bokeh server and set up event handlers with .on_change (or for some widgets, .on_click).
I couldn't really find that much on running jupyter notebook and bokeh server, but this issue seems to discuss that possibility. It also mentions bokeh.application but I've never used that, so no idea how that works.
You also use additionally a custom js callback, which calls into the jupyter kernel and tries to execute update_plot(value), but you never defined such a function, so it does nothing.
Then you need a method to push the data to the output. I guess bokeh server can somehow do that nativly, for jupyter notebooks without the bokeh server push_notebook seems to be the solution. Note that you need show(..., notebook_handle=True) to be able to push.
Solution 1 use the bokeh server
Sliders and others widgets automatically sync their state back to python, so you can use slider.on_change. You don't need the CustomJS. Data flow should look as following:
python script -> bokeh server -> html -> userinput -> bokeh server -> python callbacks -> bokeh server updates plots
Solution 2 use bokeh sliders but sync via CustomJS
If you don't want to run a seperate process you can use the jupyter kernel to execute code in your python notebook. Dataflow:
jupyter notebook -> html -> user input -> customjs -> jupyter kernel -> python callbacks -> push_notebook to update plots
output_notebook()
N = 300
source = ColumnDataSource(data={'x':random(N), 'y':random(N)})
plot = figure(plot_width=950, plot_height=400)
plot.circle(x='x', y='y', source=source)
callback = CustomJS(code="""
if (IPython.notebook.kernel !== undefined) {
var kernel = IPython.notebook.kernel;
cmd = "update_plot(" + cb_obj.value + ")";
kernel.execute(cmd, {}, {})};
""")
slider = Slider(start=100, end=1000, value=N, step=10, callback=callback)
# must have the same name as the function that the CustomJS tries to call
def update_plot(N):
source.data={'x':random(N), 'y':random(N)}
# push notebooks to update plots
push_notebook()
layout = column(slider, plot)
# notebook_handle must be true, otherwise push_notebook will not work
h1 = show(layout, notebook_handle=True)
Solution 3 use ipywidgets
If you are not married to the bokeh widgets you can use the ipywidgets which are designed for interactivity in the jupyter notebook. The data flow is as following:
jupyter notebook -> html -> user input -> ipywidgets sync automatically -> python callbacks -> push_notebook
I use here interact but the other widgets should work as expected.
from ipywidgets import interact
output_notebook()
N = 300
source = ColumnDataSource(data={'x':random(N), 'y':random(N)})
plot = figure(plot_width=950, plot_height=400)
plot.circle(x='x', y='y', source=source)
def update_plot(v):
N = v
print(N)
source.data={'x':random(N), 'y':random(N)}
# push changed plots to the frontend
push_notebook()
# notebook_handle must be true so that push_notebook works
show(plot, notebook_handle=True)
Note that you need to install ipywidgets properly, which inlcudes calling jupyter nbextension enable --py --sys-prefix widgetsnbextension if you are not using conda. For details see the documentation
I suppose your question relates to the server although you have both a CustomJS and a server callback.
I am not familiar with the previous way of doing bokeh server in notebook (push_notebook).
The new way would be like this: you wrap your code in a function taking one parameter (a document) and your call to add_layout is made on that document. Then you build an app with that function and show it.
This gives:
from bokeh.models import ColumnDataSource, Slider
from bokeh.layouts import column
from bokeh.plotting import figure, show, output_notebook
from numpy.random import random
from bokeh.application import Application
from bokeh.application.handlers import FunctionHandler
output_notebook()
def modify_doc(doc):
N = 300
source = ColumnDataSource(data={'x':random(N), 'y':random(N)})
plot = figure(plot_width=950, plot_height=400)
plot.circle(x='x', y='y', source=source)
slider = Slider(start=100, end=1000, value=N, step=10)
def callback(attr, old, new):
N = new # but slider.value would also work
source.data={'x': random(N), 'y': random(N)}
slider.on_change('value', callback)
layout = column(slider, plot)
doc.add_root(layout)
app = Application(FunctionHandler(modify_doc))
show(app, notebook_url="localhost:8888")
Related
I am trying to build an interactive data visualization tool using bokeh layouts, but I am running into issues when generating and visualizing the plots. When running bokeh serve --show MWE1.py, I get the following error message "Only LayoutDOM items can be inserted into a column. Tried to insert: None of type " and no plots are generated in my browser window.
When running the code from the command python MWE1.py a plot is generated in a browser window, but no slider bar is present. I have also tried to remove the column layout tool from curdoc() but this didn't seem to help. Is there an issue passing functions that generate plots through curdoc(), and if so, is there an alternative solution?
(As an aside, I have also tried several of the tutorials and examples available online, all of which have worked as intended)
See MWE below:
import bokeh
from bokeh.io import curdoc
from bokeh import layouts
from bokeh.layouts import column,row,gridplot
from bokeh.models import ColumnDataSource, Slider
from bokeh.io import output_file
from bokeh.plotting import figure,show
x=[1, 2, 3]
y=[4, 5, 6]
def p(x,y):
p = figure()
p.line(x,y)
show(p)
q = p(x,y)
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1)
curdoc().add_root(column(freq,q))'''
You function p is wrong:
It doesn't return the plot
It calls show which doesn't work with bokeh serve
Try this instead
def p(x,y):
p = figure()
p.line(x,y)
return p
I am having struggles with making an interactive plot in Jupyter Notebook with the use of Bokeh. I want to plot a map of the world and display the development of some data over time. I succeeded in making a plot and having a slider to adjust the year, but as I change the slider, the slider value won't update. The code for the slider is below:
#creating the data source as a dict
source = ColumnDataSource({
'x': p_df['x'],
'y': p_df['y'],
'Country': p_df['Country'],
'nkill': p_df['nkill']
})
#making a slider and assign the update_plot function to changes
slider = Slider(start=start_yr, end=end_yr, step=1, value=start_yr, title='Year')
slider.on_change('value',update_plot)
#the update_plot function which needs to run based on the new slider.value
def update_plot(attr, old, new):
#Update glyph locations
yr = slider.value
Amountkills_dt_year = p_df[p_df['Year'] ==yr]
new_data = {
'x': Amountkills_dt_year['x'],
'y': Amountkills_dt_year['y'],
'Country': Amountkills_dt_year['Country'],
'nkill': Amountkills_dt_year['nkill']
}
source.data = new_data
#Update colors
color_mapper = LinearColorMapper(palette='Viridis256',
low = min(Amount_of_Terrorist_Attacks['nkill']),
high = max(Amount_of_Terrorist_Attacks['nkill']))
Where I want to update the plot with the update_plot() function. I tried the solution in Python bokeh slider not refreshing plot but I still encoutered the same error.
Bokeh widgets like sliders don't work in jupyter notebooks (at least, not without using some javascript). As the documentation says:
To use widgets, you must add them to your document and define their functionality. Widgets can be added directly to the document root or nested inside a layout. There are two ways to program a widget’s functionality:
Use the CustomJS callback (see JavaScript Callbacks). This will work in standalone HTML documents.
Use bokeh serve to start the Bokeh server and set up event handlers with .on_change (or for some widgets, .on_click).
As #bigreddot hints, you will need to use the bokeh server or else
perhaps some of the features in the discussion of jupyter interactors that are discussed here.
I'm using Jupyter Notebook and trying to create an interactive plot. I really like how simple the ipywidgets.interactive is to use and having the ability to lay things out in VBox or HBox. The problem I'm having is once I download as html the ipywidgets.interactive is not updating my plot.
Here is what I have:
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import plotly.graph_objs as go
import plotly.offline as py
import numpy as np
from IPython.display import display
py.init_notebook_mode()
xs = np.linspace(0,6,100)
ys = np.sin(xs)
scatter = go.Scatter(
x = xs,
y = ys
)
data = [scatter]
layout = go.Layout(title='test')
fig = go.FigureWidget(data=data, layout=layout)
slider = widgets.FloatRangeSlider(
min=1,
max=6,
step=.1,
description='desc'
)
def update_b(b):
fig.data[0].y = np.sin(xs+b)
vb = widgets.VBox((fig, interactive(update_b, b=(1, 6, .1))))
vb.layout.align_items='center'
# This displays it and allows it to be interactive, but only when I have it as .ipynb,
# not when I download as html
display(vb)
The way I am saving as html is:
1. Widgets > Save Notebook Widget State
2. From cmd: jupyter nbconvert --to html test_plot.ipynb
I have also done the following to enable the widget extension:
jupyter nbextension enable --py widgetsnbextension
Enabling notebook extension jupyter-js-widgets/extension...
- Validating: ok
After everything this is what I get:
The thing is the slider is movable but it does not update the graph. The graph is also able to be manipulated through zoom, etc. like normal with plotly. This leads me to believe there is something wrong with the way I've used interactive.
Any ideas?
Unfortunately this does not work this way, the function that links the slider with the plot is written in python and executes in the python kernel, so when you convert to a static html this function does not exist anymore.
I am not aware of some kind of python to javascript translator that allows these kind of functions to run without a python kernel, although plotly's Dash seems to be doing something in this line (see this issue). If you can put up a server you can use Voila or something similar to make the notebook look like a web page.
I'm not using plotly, however, try adding some line magic, like "widget" which makes the graph interactive...
%matplotlib widget
%matplotlib widget
from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot(x, np.sin(x))
def update(w = 1.0):
line.set_ydata(np.sin(w * x))
fig.canvas.draw()
interact(update);
screenshot of notebook
How can I create an interactive bar plot with bokeh through a selection widget on Jupyter Notebook?
Why the Notebook raise the following error:
"RuntimeError: Models must be owned by only a single document, Title(id='1044', ...) is already in a doc
ERROR:tornado.access:500 GET /autoload.js?bokeh-autoload-element=1002&bokeh-absolute-url=http://localhost:54277&resources=none (::1) 117.01ms"
I read carefully this example from github and this similar situation from a Google Bokeh Group, in the latter they run a bokeh server not a the jupyter kernel
output_notebook()
dct={'Date' : ["2018-01-07", "2018-01-12", "2018-01-13", "2018-01-14", "2018-01-20", "2018-01-24"],'Activity' : ['A','B','A','B','A','B'],'Count' : [1, 2, 5, 3, 7, 1]}
df=pd.DataFrame(dct)
activity_list=df['Activity'].unique().tolist().copy()
activity_selected='A'
def modify_doc(doc):
def make_plot(cdf):
plot = figure()
plot.vbar(x=cdf.Date, top=cdf.Count, width=0.9)
push_notebook()
show(plot, notebook_handle = True)
return plot
def update_plot(attr, old, new):
activity = select.value
sdf = df.copy()
sdf = sdf[sdf['Activity'] == activity]
layout.children[0] = make_plot(sdf)
select = Select(title='Select Activity', value=activity_selected, options=activity_list)
select.on_change('value', update_plot)
p=make_plot(df)
layout=column(select, p)
doc.add_root(layout)
show(modify_doc)
What I expect is something like this in the snapshoot:
I am using Bokeh 1.0.4
It's possible we need to make some documentation improvements, because there are several parts of your code that do not make sense.
push_notebook is complementary to showing a real Bokeh server app (i.e. passing modify_doc to show). I can't think of any situation where it would make sense to use them together. The Bokeh server app capability is a strict superset of push_notebook, so since you are already making a Bokeh server app, you should just update everything in the standard way.
show should never be called inside the Bokeh server app code (in this case, inside modify_doc) This is in fact the proximate cause of the exception you are getting. You should
You should not make a new plot every time! The entire purpose of both push_notebook and the Bokeh server is that updates can happen efficiently without making a whole new plot every time. You should be updating the data and attributes of the existing plot.
There is a complete wokring example of a Bokeh server app in a notebook here:
https://github.com/bokeh/bokeh/blob/master/examples/howto/server_embed/notebook_embed.ipynb
You should study and emulate that as it represents best practice.
The correct code for selecting the plot through the Select widget is:
activity_list=df['Activity'].unique().tolist().copy()
df['Date']=pd.to_datetime(df['Date'])
activity_selected='A'
def modify_doc(doc):
df_r=df.copy()
source = ColumnDataSource(data=df_r)
plot=figure(title='Daily Hours',x_axis_type="datetime")
plot.vbar(x="Date", top="Count",source=source, width=4)
def update_plot(attr, old, new):
activity = select.value
data = df_r[df_r['Activity'] == activity]
source.data = ColumnDataSource(data=data).data
select = Select(title='Select Activity', value=activity_selected, options=activity_list)
select.on_change('value', update_plot)
layout=column(select, plot)
doc.add_root(layout)
show(modify_doc)
And this will be the output that you see:
I want to use a text input widget in a jupyter notebook with autocompletion. I therefore used AutocompleteInput() from bokeh.models.widgets.inputs.
from bokeh.models.widgets.inputs import AutocompleteInput
from bokeh.io import output_notebook
from bokeh.plotting import show
output_notebook()
txt_input = AutocompleteInput(completions=['val1', 'val2'])
show(txt_input)
Displaying the widget and autocompletion works fine, but how can I access the value of the input widget upon change? txt_input.value only returns the default value (an empty string).
As of Bokeh 0.12.3, fuller integration of Bokeh widgets in the Jupyter notebook is still an open issue.
However, there are some workarounds, though they may be considered somewhat clunky. Here is a CustomJS callback you can pass to the widget that will set the value of a python value:
from bokeh.models import CustomJS
callback = CustomJS(code="""
if (IPython.notebook.kernel !== undefined) {
var kernel = IPython.notebook.kernel;
cmd = "widget_value = '" + cb_obj.value + "'";
kernel.execute(cmd, {}, {});
}
""")
The result looks like:
The value of the cmd variable in the CustomJS code is string of python code that will be executed in your currently running Jupyter kernel. If you need to call some python function, e.g., you could do that too.