如何在 Bokeh 中将多个数据源绘制在一张图中,Python 3.6?

How to plot multiple data sources in one figure in Bokeh, Python 3.6?

我正在使用 Bokeh 在 python 中制作 pca 双图。我想在图中添加文本,以便它或多或少看起来像图像(忽略红线):

)。 但是我不知道如何在散景中做到这一点。

如果我尝试像这样创建一个数据源:

data = {'PC1': x_scale*xs, 'PC2':  y_scale*ys , 'cluster': [str(x) for x in comments_df.kmeans_10], 
    'C1': components[0,:], 'C2': components[1,:], 'words':wordlist}
source = ColumnDataSource(data)

它开始抱怨我有不同的列长度(我知道)。而且它不会创建情节

BokehUserWarning: ColumnDataSource's columns must be of the same length. Current lengths: ('C1', 5775), ('C2', 5775), ('PC1', 16555), ('PC2', 16555), ('cluster', 16555), ('words', 5775)

我的另一个想法是创建两个数据源:

data = {'PC1': x_scale*xs, 'PC2':  y_scale*ys , 'cluster': [str(x) for x in comments_df.kmeans_10]}
source = ColumnDataSource(data)

data2 = {'C1': components[0,:], 'C2': components[1,:], 'words':wordlist}
source2 = ColumnDataSource(data2)

但是,在这种情况下,我在绘图时遇到错误。我的代码:

plot = Plot(plot_width=600, plot_height=600, tools = [PanTool(), WheelZoomTool(), BoxZoomTool(), ResetTool()])


## PCA loadings
glyph = Circle(x="PC1", y="PC2", fill_color=cmap)
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')
plot.xaxis.axis_label = 'PC1'

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')
plot.yaxis.axis_label = 'PC2'

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

## PCA components
word_glyph = Text(x="C1", y="C2", text="words", text_color="red")
plot.add_glyph(source2, glyph)

# Show
show(plot)

错误:

ERROR:bokeh.core.validation.check:E-1001 (BAD_COLUMN_NAME): Glyph refers to nonexistent column name. This could either be due to a misspelling or typo, or due to an expected column being missing. : key "fill_color" value "cluster", key "x" value "PC1" (closest match: "C1"), key "y" value "PC2" (closest match: "C2") [renderer: GlyphRenderer(id='2028', ...)]

我可能忽略了某些内容或使用了不正确的术语进行搜索,所以如果有人能告诉我该怎么做,那就太好了。谢谢!

您正在配置第一个字形两次,第二次使用了错误的数据源:

plot.add_glyph(source2, glyph)

想必您打​​算:

plot.add_glyph(source2, word_glyph)

顺便说一句,您使用的是非常低的级别 bokeh.models API,这非常冗长。有一个更高级别的 bokeh.plotting API ,它通常总是更少的等效输出代码,并且也使很多这样的错误不可能发生(因为它为您协调了字形和数据源)。