我试图在散景中绘制几个图,但出现以下错误:
RuntimeError: Models must be owned by only a single document, Selection(id='1057', ...) is already in a doc.
我知道这是在多个文档中尝试使用相同对象时引起的,但我不知道在哪里进行操作。这是完整的(简化的)代码。
我正在使用Bokeh 1.4.0。
from bokeh.plotting import figure, show
from bokeh.layouts import row, gridplot
from bokeh.models import ColumnDataSource
from bokeh.io import output_file
import pandas as pd
feature_groups = [['ciao'],['bye']]
df = pd.DataFrame.from_dict({'x':[0,1,2,3,4], 'y':[2,3,4,5,6]})
x_test = [0,1,2,3,4]
y_test = [2,3,4,5,6]
source = ColumnDataSource(df)
for features_columns in feature_groups:
output_file('features_labels' + features_columns[0] +'.html')
p = []
for k,f in enumerate(features_columns):
p_k = figure(title=f)
p_k.circle(x=f, y='ki', line_width=2, source=source,fill_alpha=0.5,line_alpha=0.5)
p_k.circle_cross( x=x_test, y=y_test, color='red',fill_alpha=0.5,line_alpha=0.5)
p_k.circle_cross( x = x_test, y = y_test, color='green',fill_alpha=0.5,line_alpha=0.5)
p_k.xaxis.axis_label = f
p_k.yaxis.axis_label = 'ki'
p.append(p_k)
grid = gridplot(p, ncols=2)
show(grid)
先谢谢您
1)就像错误一样,表示每个Bokeh模型(在这种情况下为ColumnDataSource
实例)只能添加到Bokeh Document
中一次,因此只需将source = ColumnDataSource(df)
移动到for
循环即可。
编辑(感谢bigreddot):显然,您只能在同一散景source
中的字形和绘图之间共享同一Document
,而不能在不同文档之间共享。像output_file
,save
和show
之类的方法会隐式创建一个新的Bokeh Document
,因此在原始代码中结合使用相同的source
和两个output_file
语句会导致问题
2),您引用的是ColumnDataSource中不存在的字段,例如'ki'等。我将其替换为x='x'
和y='y'
请参见下面的更正和工作代码:
from bokeh.plotting import figure, show
from bokeh.layouts import row, gridplot
from bokeh.models import ColumnDataSource
from bokeh.io import output_file
import pandas as pd
feature_groups = [['ciao'],['bye']]
df = pd.DataFrame.from_dict({'x':[0,1,2,3,4], 'y':[2,3,4,5,6]})
x_test = [0,1,2,3,4]
y_test = [2,3,4,5,6]
for features_columns in feature_groups:
output_file('features_labels' + features_columns[0] +'.html')
p = []
source = ColumnDataSource(df)
for k,f in enumerate(features_columns):
p_k = figure(title=f)
p_k.circle(x='x', y='y', line_width=2, source=source,fill_alpha=0.5,line_alpha=0.5)
p_k.circle_cross( x=x_test, y=y_test, color='red',fill_alpha=0.5,line_alpha=0.5)
p_k.circle_cross( x = x_test, y = y_test, color='green',fill_alpha=0.5,line_alpha=0.5)
p_k.xaxis.axis_label = f
p_k.yaxis.axis_label = 'ki'
p.append(p_k)
grid = gridplot(p, ncols=2)
show(grid)