bokeh RuntimeError: Models must be owned by only a single document

The RuntimeError “Models must be owned by only a single document” occurs in Bokeh when you try to use a Bokeh model that is already associated with one document in another document. Bokeh models can only belong to a single document at a time. When this error arises, it indicates that the model has already been added to a document and cannot be added to a different one.

To resolve this issue, you can create a new instance of the model for each document or use the clone() function from the bokeh.models module to create a copy of the model. This will ensure that each document has its own separate instance of the model.

Here’s an example to demonstrate how to use the clone() function:

from import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, CDSView, IndexFilter
from bokeh.models import clone

# Prepare the data
data = {'x': [1, 2, 3, 4, 5],
        'y': [2, 5, 8, 2, 7]}

source = ColumnDataSource(data)
view = CDSView(source=source, filters=[IndexFilter([0, 2, 4])])

# Create the first plot
plot1 = figure(title="Plot 1", x_axis_label="x", y_axis_label="y")'x', 'y', source=source, view=view, size=10)

# Clone the view for use in the second plot
cloned_view = clone(view)

# Create the second plot
plot2 = figure(title="Plot 2", x_axis_label="x", y_axis_label="y")'x', 'y', source=source, view=cloned_view, size=10, color="red")



In this example, we first create a ColumnDataSource and a CDSView with an IndexFilter. We use these in the first plot. Then, we clone the CDSView using the clone() function and use the cloned_view in the second plot. This ensures that both plots have their own separate instances of the view, avoiding the RuntimeError.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.