bokeh, ipywidgets, jupyterlab and voilà - python

I'm trying to create a webapp using bokeh. Mostly, it will consist of markdown text and some figures. Right now I'm stuck a getting voilà to show two bokeh figures side by side. Within the notebook everything runs smoothly, but in the voilà visualization I see errors like
Javascript Error: Error rendering Bokeh model: could not find #5db0eeb2-830f-4e00-b6fe-552a45536513 HTML tag
Now, if I try in classic jupyter notebook (within jupyter-lab Help -> Launch Classic Notebook), then it renders fine. However, when it is served from github, I get again javascript errors.
A MWE within jupyterlab but non-working in voilà is:
import numpy as np
import ipywidgets as widgets
import bokeh.plotting
from bokeh.io import output_notebook, show
from bokeh.models import ColumnDataSource, Line
output_notebook()
t = np.arange(10)
signal = np.arange(10)
f_1 = bokeh.plotting.figure(plot_width=400, plot_height=300, toolbar_location=None)
data_source_1 = ColumnDataSource(data=dict(t=t, signal=signal))
f_1.line(x='t', y='signal', source=data_source_1)
out_1 = widgets.Output()
with out_1:
show(f_1)
f_2 = bokeh.plotting.figure(plot_width=400, plot_height=300, toolbar_location=None)
data_source_2 = ColumnDataSource(data=dict(t=t, signal=2*signal))
f_2.line(x='t', y='signal', source=data_source_2)
out_2 = widgets.Output()
with out_2:
show(f_2)
widgets.HBox([out_1, out_2])
This is meant to be part of mini-lecture on analog modulations: the classic notebook version works fine, but when I try to use voilà-served version (click the Voilà button there or just go to this other link) I hit the same problem.
Any clue?

Related

Interactive graphical visualization with matplotlib

I want to show specific data (not the columns I used in plotting my scatter plot but other columns in the dataframe) whenever I hover my mouse on each data point using matpotlib. I don't want to use plotly because I need to implement another part of matplotlib.
I wrote the following script but it is not implementing the hovering part when I run it in my jupyter notebook.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib widget
# Load sample data
diamonds = sns.load_dataset('diamonds')
# Create a scatter plot with hue and use matplotlib to display the specific column values when hovering over a datapoint
sns.scatterplot(x="carat", y="price", hue="cut", data=diamonds)
def hover(event):
# Get the current mouse position
ax = event.inaxes
x, y = event.xdata, event.ydata
# Find the nearest datapoint
distances = ((diamonds['carat'] - x)**2 + (diamonds['price'] - y)**2)
idx = distances.idxmin()
# Display the specific column values in a pop-up window
text = f"Cut: {diamonds.loc[idx, 'cut']}\n" \
f"Clarity: {diamonds.loc[idx, 'clarity']}\n" \
f"Color: {diamonds.loc[idx, 'color']}"
plt.gcf().text(x, y, text, ha='left', va='bottom', fontsize=10, backgroundcolor='white', alpha=0.7)
# Connect the hover function to the figure
fig = plt.gcf()
fig.canvas.mpl_connect("motion_notify_event", hover)
# Show the plot
plt.show()
This is easier with mplcursors. There's a similar example of extracting the data and labels for the annotation from a dataframe to plug into. Implemented with your example it is:
%matplotlib ipympl
# based on https://mplcursors.readthedocs.io/en/stable/examples/dataframe.html
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.patheffects import withSimplePatchShadow
import mplcursors
df = sns.load_dataset('diamonds')[:10]
sbsp = sns.scatterplot(x="carat", y="price", hue="cut", data=df)
def show_hover_panel(get_text_func=None):
cursor = mplcursors.cursor(
hover=2, # Transient
annotation_kwargs=dict(
bbox=dict(
boxstyle="square,pad=0.5",
facecolor="wheat",
edgecolor="#ddd",
linewidth=0.5,
path_effects=[withSimplePatchShadow(offset=(1.5, -1.5))],
),
linespacing=1.5,
arrowprops=None,
),
highlight=True,
highlight_kwargs=dict(linewidth=2),
)
if get_text_func:
cursor.connect(
event="add",
func=lambda sel: sel.annotation.set_text(get_text_func(sel.index)),
)
return cursor
def on_add(index):
item = df.iloc[index]
parts = [
f"Cut: {item.cut}", # f"Cut: {diamonds.loc[idx, 'cut']}\n"
f"Clarity: {item.clarity}", # f"Clarity: {diamonds.loc[idx, 'clarity']}\n"
f"Color: {item.color}", #f"Color: {diamonds.loc[idx, 'color']}"
]
return "\n".join(parts)
sbsp.figure.canvas.header_visible = False # Hide the Figure name at the top of the figure;based on https://matplotlib.org/ipympl/examples/full-example.html
show_hover_panel(on_add)
plt.show();
That's for running it in JupyterLab where ipympl has been installed.
For running it in Jupyter Notebook at present, change the first line to %matplotlib notebook.
I saw it be smoother in JupyterLab.
I'll point to ways to try the code in both interfaces without installing anything on your system below.
(Your approach may be able to work with more incorporation of things here. However, there's already a very similar answer with mplcursors)
(The places and steps to run the code outlined below were worked out primarily for the Matplotlib option here yesterday. Noting that here as there were some quirks to the ipympl offering launching and I worry that I may miss updating each place if something changes.)
Try it in JupyterLab in conjunction with ipympl without touching your system
This will allow you to try the code in JupyterLab without installing anything on your own system.
Go to here. Sadly the link currently goes to a dead end and doesn't seem to build a new image right now. Fortunately, right now this offering works for launching.
When that session opens, run in a notebook %pip install mplcursors seaborn. Let that installation command run to install both mplcursors and seaborn and then restart the kernel.
Make a new cell and paste in the code from above and run it.
Try it Jupyter Notebook classic interface without touching your system
This will allow you to try the code in the present classic Jupyter Notebook interface (soon-to-be more-often-referenced as 'the document-centric interface' as the underlying machinery for Jupyter Notebook 7 will use JupyterLab components) without installing anything on your own system.
Go here and press 'launch binder'. A temporary, remote session will spin up served via MyBinder.
Make a new cell and simply add %matplotlib notebook at the top of the cell. Then add the code above to the cell, leaving off the first line of the suggested code, so that you effectively substitute %matplotlib notebook in place of %matplotlib ipympl.
Run the cell.

VSCode notebook silently failing show(modify_doc)

When using the built-in Jupyter notebook editor in Visual Studio Code and using the show(modify_doc) way of plotting, the result is not displayed. Showing individual plots does work.
I tried Googling and reading through the documentation but I couldn't find a solution anywhere. Hopefully someone knows what is wrong here.
(Example taken from the Internet)
Importing necessary modules:
from bokeh.io import push_notebook, show, output_notebook
from bokeh.layouts import row, gridplot
from bokeh.plotting import figure, show, output_file, curdoc
from bokeh.document import Document
output_notebook()
import numpy as np
This does not work as intended in VSCode but it does in the official Jupyter Notebook. I added a print statement as a test and it also does not get printed in VSCode.
def modify_doc(doc):
print("Test")
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p1 = figure(title="Legend Example", tools=TOOLS)
p1.circle(x, y, legend="sin(x)")
p1.circle(x, 2*y, legend="2*sin(x)", color="orange")
p1.circle(x, 3*y, legend="3*sin(x)", color="green")
# Add everything to the layout
layout = row(p1)
# Add the layout to curdoc
doc.add_root(layout)
show(modify_doc)
The following code does run:
x2 = np.linspace(0, 4*np.pi, 100)
y2 = np.sin(x2)
TOOLS2 = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p2 = figure(title="Legend Example", tools=TOOLS2)
p2.circle(x2, y2, legend="sin(x)")
p2.circle(x2, 2*y2, legend="2*sin(x)", color="orange")
p2.circle(x2, 3*y2, legend="3*sin(x)", color="green")
show(p2)
I had a similar problem. For me it used to work to output the bokeh figure in a jupyter notebook cell with show() in VS Code. But suddenly it stopped working even though I didn't make changes to the code (or reverted the changes to be more precise).
I could resolve the issue by changing the Anaconda environment to another environment and then switching back to the proper environment (see screenshot below).

Python Bokeh 2.0.1 - a JS callback for UndoTool?

I've recently started working with Bokeh 2.0.1 on Anaconda. My overarching goal is to visualize some datasets as self-contained html files, with Bokeh menu tools.
In addition to existing tools, I've added a functionality where DoubleTap places a label on the plot at the tap's coordinates. It works as planned, however, I want this operation to be undoable via the standard Bokeh UndoTool. I tried adding a CustomJS callback to the UndoTool instance of the figure in question. However, I can't get this to work - when I click on the Undo button in the figure, the added label doesn't disappear. Apparently, the "undoing" callback doesn't get triggered.
I know that the "undoing" callback is not a problem, because I've also bound it to a button and it works as planned.
The concept code is:
from bokeh.plotting import figure
from bokeh.events import MenuItemClick, ButtonClick
from bokeh.models import CustomJS, Button
from bokeh.events import DoubleTap
add_label = CustomJS(--something--)
remove_label = CustomJS(--something else--)
f_h = figure(tools='undo')
f_h.js_on_event(DoubleTap, add_label) # Works as planned - adds a label on a double tap
loc_button = Button()
loc_button.js_on_event(ButtonClick, remove_label) # Also works as planned - removes the last added label
f_h.tools[0].js_on_event(MenuItemClick, remove_label) # Doesn't work - aside from the standard scaling undo behavior nothing happens
Thanks in advance,
P.V.
There's a reset event:
from bokeh.io import show
from bokeh.models import CustomJS
from bokeh.plotting import figure
p = figure(tools='reset')
p.circle(x=0, y=0)
p.js_on_event('reset', CustomJS(code="console.log('Resetting!')"))
show(p)

How to link a multiselect widget to a datatable using bokeh in a jupyter notebook?

I'm attempting to connect a datatable with a multiselect widget in bokeh. I've searched around and gathered that I need to develop a function to update the data source for the data table, but I seem to have two problems.
I cannot seem to access the value of the multiselect object after I click it.
I cannot seem to push the change to the notebook after receiving the change.
Here's an example of my code:
import pandas as pd
from bokeh.io import push_notebook
from bokeh.plotting import show, output_notebook
from bokeh.layouts import row
from bokeh.models.widgets import MultiSelect, DataTable, TableColumn
from bokeh.models import ColumnDataSource
output_notebook()
df=pd.DataFrame({'year':[2000,2001,2000,2001,2000,2001,2000,2001],
'color':['red','blue','green','red','blue','green','red','blue'],
'value':[ 0,1,2,3,4,5,6,7]})
columns=[TableColumn(field=x, title=x) for x in df.columns]
source=ColumnDataSource(df)
data_table=DataTable(source=source,columns=columns)
years=[2000,2001,2000,2001,2000,2001,2000,2001]
## MultiSelect won't let me store an integer value, so I convert them to strings
multi=MultiSelect(title="Select a Year", value=['2000','2001'],options=[str(y) for y in set(years)])
def update(attr,old, new):
yr=multi.value
yr_vals=[int(y) for y in yr]
new_data=df[df.year.isin(yr_vals)]
source.data=new_data
push_notebook(handle=t)
multi.on_change('value',update)
t=show(row(multi,data_table),notebook_handle=True)
push_notebook is uni-directional. That is, you can only push changes from the IPython kernel, to the JavaScript front end. No changes from the UI are propagated back to the running Python kernel. In other words, on_change is not useful (without more work, see below) If you want that kind of interaction, there are a few options:
Use ipywidgets with push_notebook. Typically this involved the interact function to automatically generate a simple UI with callbacks that use push_notebook to update the plots, etc. based on the widget values. Just to be clear, this approach uses ipywidgets, which are not Bokeh built-in widgets. You can see a full example notebook here:
https://github.com/bokeh/bokeh/blob/master/examples/howto/notebook_comms/Jupyter%20Interactors.ipynb
Embed a Bokeh server application. The Bokeh server is what makes it possible for on_change callbacks on Bokeh widgets to function. Typically this involves making a function that defines the app (by specifying how a new document is created):
def modify_doc(doc):
df = sea_surface_temperature.copy()
source = ColumnDataSource(data=df)
plot = figure(x_axis_type='datetime', y_range=(0, 25))
plot.line('time', 'temperature', source=source)
def callback(attr, old, new):
if new == 0:
data = df
else:
data = df.rolling('{0}D'.format(new)).mean()
source.data = ColumnDataSource(data=data).data
slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
slider.on_change('value', callback)
doc.add_root(column(slider, plot))
Then calling show on that function:
show(modify_doc)
A full example notebook is here:
https://github.com/bokeh/bokeh/blob/master/examples/howto/server_embed/notebook_embed.ipynb
(Hacky option) some people have combined CustomJS callbacks with Jupyers JS function kernel.execute to propagate values back to the kernel.

Adding clickable circle in bokeh plots

I am trying to add certain callbacks to a circles which are plotted on bokeh plot. Each circle is associated with certain record from columndatasource. I want to access that record whenever corresponding circle is clicked. Is there any way to add callbacks to circles in bokeh?
How can i do it?
I am using following code
fig =figure(x_range=(-bound, bound), y_range=(-bound, bound),
plot_width=800, plot_height=500,output_backend="webgl")
fig.circle(x='longitude',y='latitude',size=2,source=source,fill_color="blue",
fill_alpha=1, line_color=None)
Then you want to add an on_change callback to the selected property of the data source. Here is a minimal example. As stated above, python callbacks require the Bokeh server (that is where python callbacks actually get run, since the browser knows nothing of python), so this must be run e.g. bokeh serve --show example.py (Or, if you are in a notebook, following the pattern in this example notebook).
# example.py
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
source = ColumnDataSource(data=dict(x=[1,2,3], y=[4,6,5]))
p = figure(title="select a circle", tools="tap")
p.circle('x', 'y', size=25, source=source)
def callback(attr, old, new):
# This uses syntax for Bokeh >= 0.13
print("Indices of selected circles: ", source.selected.indices)
source.selected.on_change('indices', callback)
curdoc().add_root(p)

Categories

Resources