0
votes

I want to plot multiple plots in bokeh? For example, this code does what I want in very inefficient way. I want the same thing but maybe with a loop?, or any bokeh function I am not aware of.

p = figure(...)

p1 = figure(...)

p2 = figure(...)

y = [[1,2,3,4,5,6],[7,8,9,10,11,12],[3,1,4,3,2,5]]
x = [[2,3,4,5,6,7],[8,9,10,11,12,13],[1,4,3,2,5,6]]


plots = []
p.line(x=np.arange(6), y=y[0], color='#CE1141', legend='Prediction')
p.line(x=np.arange(6,12), y=x[0], color='#006BB6', legend='Prediction')
plots.append(p)

p1.line(x=np.arange(6), y=y[1], color='#CE1141', legend='Prediction')
p1.line(x=np.arange(6,12), y=x[1], color='#006BB6', legend='Prediction')
plots.append(p1)

p2.line(x=np.arange(6), y=y[2], color='#CE1141', legend='Prediction')
p2.line(x=np.arange(6,12), y=x[2], color='#006BB6', legend='Prediction')
plots.append(p2)


show(column(*plots))

Basically, I have two 2D array and I want to plot the pair of them in one plot. I tried it in a for loop but it plots every thing in a plot and shows the same plot multiple times, I tried something like:

for i in range(3):
    p.line(x=np.arange(6), y=y[i], color='#CE1141', legend='Prediction')
    p.line(x=np.arange(6,12), y=x[i], color='#006BB6', legend='Prediction')
p.show()

I can see the problem here, everything is plotted in p, so at the end I get a plot where everything is plotted.

I also tried creating an array and appending plot in to it, as shown in the working inefficient example above, but it shows blank plot for first columns and plots single plot with everything in it at last.

1

1 Answers

4
votes

You could do it e.g. this way, using list comprehension (Bokeh v1.3.0):

from bokeh.plotting import figure, show
from bokeh.layouts import gridplot
import numpy as np

plots = [figure() for i in range(3)]
glyphs = [plot.line(np.arange(10), np.random.random(10)) for plot in plots for i in range(2)]
show(gridplot(children = plots, ncols = 1, merge_tools = False))

Or if you really need a for loop:

from bokeh.plotting import figure, show
from bokeh.layouts import column
import numpy as np

plots = []
for i in range(3):
    p = figure()
    glyphs = [p.line(np.arange(10), np.random.random(10)) for j in range(2)]
    plots.append(p)
show(column(*plots))

The point is that you can pass to show() function only a single model object so you need to pack all plots into some layout component like gridplot, column or row. It's also good to know that each show() creates implicitly a Bokeh document to which all models that you are passing to show() function are attached to. In Bokeh for each document you can attach each model only once. So e.g. you couldn't do show(column(*plots)) more than once in the same script without explicitly creating a new document.