Migrating code from Bokeh 0.10.0 to 0.11.0 - python

I have the below example of real time streaming in Bokeh 0.10.0 from reddit thread.
import time
from random import shuffle
from bokeh.plotting import figure, output_server, cursession, show
# prepare output to server
output_server("animated_line")
p = figure(plot_width=400, plot_height=400)
p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], name='ex_line')
show(p)
# create some simple animation..
# first get our figure example data source
renderer = p.select(dict(name="ex_line"))
ds = renderer[0].data_source
while True:
# Update y data of the source object
shuffle(ds.data["y"])
# store the updated source on the server
cursession().store_objects(ds)
time.sleep(0.5)
I know that there is no cursession from 0.11.0 version. What would the code be like in Bokeh 0.11.0? Here is my attempt at it. Am I missing something? Basically, what I want the below code to do is to run as an app so that when I provide live streaming data, I can update the source and plot it realtime.
from bokeh.models import ColumnDataSource, HoverTool, HBox, VBoxForm
from bokeh.plotting import Figure, output_file, save
from bokeh.embed import file_html
from bokeh.models import DatetimeTickFormatter, HoverTool, PreText
from bokeh.io import curdoc
from bokeh.palettes import OrRd9, Greens9
plot = Figure(logo=None, plot_height=400, plot_width=700, title="",
tools=["resize,crosshair"])
source = ColumnDataSource(data=dict(x=[], y=[]))
plot.line([1,2,3], [10,20,30], source=source, legend='Price', line_width=1, line_color=OrRd9[0])
curdoc().add_root(HBox(plot, width=1100))

you probably want to add a periodic callback, something like:
def update():
ds.data["y"] = shuffle(y)
curdoc().add_periodic_callback(update, 500)
But also you actually need to put the data into the column data source, , and tell line the columns you want to use, instead of passing list literals to figure:
source = ColumnDataSource(data=dict(x=[1,2,3], y=[10,20,30]))
plot.line('x', 'y', source=source, legend='Price',
line_width=1, line_color=OrRd9[0])

Related

Fix right-side of plot in place when zooming in/out

When I zoom out the following Bokeh plot:
A bunch of whitespace is added to both sides of the data:
How can I make it so that the right-hand side of the plot is fixed, so that zooming out will only create whitespace on the left-hand side? For example, this is my desired zoom-out look:
This is the code that initializes the plot:
from bokeh.plotting import figure, curdoc
from bokeh.driving import linear
from bokeh.models.tools import PanTool, WheelZoomTool
p = figure(sizing_mode="stretch_both", y_axis_location="right", x_axis_type="datetime")
pan_tool = p.select(dict(type=PanTool))
pan_tool.dimensions="width"
zoom_tool = p.select(dict(type=WheelZoomTool))
zoom_tool.dimensions="width"
This can be done with a CustomJS callback. Define a ColumnDataSource as source and look for the maximum x value on thof the source. If you have multiple renderers or multiple sources, you have to find the mximum of the maximums.
Minimal Example
from bokeh.plotting import show, figure, output_notebook
from bokeh.models import CustomJS, Line, ColumnDataSource
output_notebook()
p = figure(width=500, height=300)
source = ColumnDataSource(dict(x=data, y=data))
p.line(x='x', y='y', source=source)
callback = CustomJS(
args=dict(p=p, source=source),
code="""
p.x_range.end = Math.max(...source.data['x'])
p.change.emit();
"""
)
p.x_range.js_on_change("end", callback)
show(p)

Bokeh change data_source aren't updated by push_notebook

I'm having trouble continuously update a shown figure. Could someone help me, please?
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import bokeh
from bokeh.io import push_notebook, show, output_notebook
from bokeh import layouts
from bokeh.plotting import figure
output_notebook()
# In[2]:
def to_data_source(y):
y = np.array(y)
x = np.arange(y.size)
return bokeh.models.ColumnDataSource({
'x': x,
'y': y
})
# In[3]:
# this will plot an empty figure
vis = figure()
handle = show(vis, notebook_handle=True)
# In[4]:
# this will plot on the empty figure
line = vis.line()
line.data_source = to_data_source(np.random.randn(30))
push_notebook(handle=handle)
# In[5]:
# this will not update the figure
line.data_source.data['y'] += np.arange(30)
push_notebook(handle=handle)
# In[6]:
# this will not update the figure
line.update(data_source=to_data_source(line.data_source.data['y'] + np.arange(30)))
push_notebook(handle=handle)
# In[7]:
# this will plot the correct figure that should've been updated to the previous `show`
show(vis)
I tried removing the old glyph and adding a new one every time, and it actually works. However, I don't understand why this simple usage that I see everywhere doesn't work here.
Also gist of the notebook here: https://gist.github.com/uduse/f2b17bc67de8fd0ee32f34a87849c8b6
Try to create the handle of the figure after creating the line from vis.
import numpy as np
import bokeh
from bokeh.io import push_notebook, show, output_notebook
from bokeh import layouts
from bokeh.plotting import figure
output_notebook()
line = vis.line()
line.data_source = to_data_source(np.random.randn(30))
## Handle defined here after adding stuff to the figure
handle = show(vis, notebook_handle=True)
push_notebook(handle=handle)
# this will NOW UPDATE the figure
line.data_source.data['y'] += np.arange(30)
push_notebook(handle=handle)
Actually, I'm not sure why exactly it behaves like this, but It should work that way.
I hope this may help you.
This is actually a known bug. See https://github.com/bokeh/bokeh/issues/8244

Plotting in Bokeh using Custom Function?

does anyone know if/how one can use a "custom" function to plot in Bokeh using the Bokeh server? For example, I know you can use something like
plot = figure(toolbar_location=None)
plot.vbar(x='x', width=0.5, bottom=0, top='y', source=source)
But how can you plot using something like
def mplot(source):
p = pd.DataFrame()
p['aspects'] = source.data['x']
p['importance'] = source.data['y']
plot = Bar(p, values='importance', label='aspects', legend=False)
return plot
My current attempt is, here:
http://pastebin.com/7Zk9ampq
but it doesn't run. I'm not worried about getting the function "update_samples_or_dataset" working yet, just the initial plot to show. Any help would be much appreciated. Thanks!
Is this what you want? Note that I did not use the Bar function imported from bokeh.charts as this does not update upon updating the data source.
If you want to stick with using Bar from bokeh.charts you need to recreate the plot each time.
Note: to run this and have updating work - you need to execute bokeh serve --show plotfilename.py from the command line.
from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.models.widgets import Button
from bokeh.plotting import ColumnDataSource, figure
import random
def bar_plot(fig, source):
fig.vbar(x='x', width=0.5, bottom=0,top='y',source=source, color="firebrick")
return fig
def update_data():
data = source.data
data['y'] = random.sample(range(0,10),len(data['y']))
source.data =data
button = Button(label="Press here to update data", button_type="success")
button.on_click(update_data)
data = {'x':[0,1,2,3],'y':[10,20,30,40]}
source = ColumnDataSource(data)
fig = figure(plot_width=650,
plot_height=500,
x_axis_label='x',
y_axis_label='y')
fig = bar_plot(fig, source)
layout = layout([[button,fig]])
curdoc().add_root(layout)
EDIT: See below a method that plots a bokeh plot but uses data from a dataframe as you wanted. It also will update the plot on each button press. Still you need to use the command bokeh serve --show plotfilename.py
from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.models.widgets import Button
from bokeh.plotting import ColumnDataSource
from bokeh.charts import Bar
import random
import pandas as pd
def bar_plot(source):
df = pd.DataFrame(source.data)
fig = Bar(df, values='y', color="firebrick")
return fig
def update_data():
data = {'x':[0,1,2,3],'y':random.sample(range(0,10),4)}
source2 = ColumnDataSource(data)
newfig = bar_plot(source2)
layout.children[0].children[1] = newfig
button = Button(label="Press here to update data", button_type="success")
button.on_click(update_data)
data = {'x':[0,1,2,3],'y':[10,20,30,40]}
source = ColumnDataSource(data)
fig = bar_plot(source)
layout = layout([[button,fig]])
curdoc().add_root(layout)
I think you still have to attach your Bar instance to a Figure instance; a Figure is a set of plots, essentially, with niceties like the toolbar.

how to loop on the graph only when button is click with bokeh and jupyter-notebook

I am running Bokeh into Jupyter notebook :
from bokeh.io import output_notebook, show
from bokeh.plotting import figure
output_notebook()
I have an example of a graph running forever thanks to the callback function
import numpy as np
from numpy import pi
from bokeh.client import push_session
from bokeh.driving import cosine
from bokeh.plotting import figure, curdoc
from bokeh.models import CustomJS, ColumnDataSource, Slider
x = np.linspace(0, 4*pi, 80)
y = np.sin(x)
p = figure()
r1 = p.line([0, 4*pi], [-1, 1], color="firebrick")
r2 = p.line(x, y, color="navy", line_width=4)
session = push_session(curdoc())
#cosine(w=0.03)
def update(step):
r2.data_source.data["y"] = y * step
r2.glyph.line_alpha = 1 - 0.8 * abs(step)
curdoc().add_periodic_callback(update, 50)
session.show(p)
session.loop_until_closed()
My problem is I would like to run/update this graph only when the user wants it (via a button or a customJS it doesn't matter how if it works!)
I don't find any option to do that. Does someone know if it possible with Bokeh ?
Thank you!

How to create a multi-line plot title in bokeh?

How do you create a multiline plot title in bokeh?... same question as https://github.com/bokeh/bokeh/issues/994
Is this resolved yet?
import bokeh.plotting as plt
plt.output_file("test.html")
plt.text(x=[1,2,3], y = [0,0,0], text=['hello\nworld!', 'hello\nworld!', 'hello\nworld!'], angle = 0)
plt.show()
Additionally, can the title text string accept rich text?
In recent versions of Bokeh, labels and text glyphs can accept newlines in the text, and these will be rendered as expected. For multi-line titles, you will have to add explicit Title annotations for each line you want. Here is a complete example:
from bokeh.io import output_file, show
from bokeh.models import Title
from bokeh.plotting import figure
output_file("test.html")
p = figure(x_range=(0, 5))
p.text(x=[1,2,3], y = [0,0,0], text=['hello\nworld!', 'hello\nworld!', 'hello\nworld!'], angle = 0)
p.add_layout(Title(text="Sub-Title", text_font_style="italic"), 'above')
p.add_layout(Title(text="Title", text_font_size="16pt"), 'above')
show(p)
Which produces:
Note that you are limited to the standard "text properties" that Bokeh exposes, since the underlying HTML Canvas does not accept rich text. If you need something like that it might be possible with a custom extension
You can add a simple title to your plot with this:
from bokeh.plotting import figure, show, output_file
output_file("test.html")
p = figure(title="Your title")
p.text(x=[1,2,3], y = [0,0,0], text=['hello\nworld!', 'hello\nworld!', 'hello\nworld!'], angle = 0)
show(p)
Addendum
Here is a working example for plotting a pandas dataframe for you to copy/paste into a jupyter notebook. It's neither elegant nor pythonic. I got it a long time ago from various SO posts. Sorry, that I don't remember which ones anymore, so I can't cite them.
Code
# coding: utf-8
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
import pandas as pd
import numpy as np
# Create some data
np_arr = np.array([[1,1,1], [2,2,2], [3,3,3], [4,4,4]])
pd_df = pd.DataFrame(data=np_arr)
pd_df
# Convert for multi-line plotting
data = [row[1].as_matrix() for row in pd_df.iterrows()]
num_lines = len(pd_df)
cols = [pd_df.columns.values] * num_lines
data
# Init bokeh output for jupyter notebook - Adjust this to your needs
output_notebook()
# Plot
p = figure(plot_width=600, plot_height=300)
p.multi_line(xs=cols, ys=data)
show(p)
Plot

Categories