使用 for 循环生成器制作具有分类值的 Bokeh 散点图

Using for loop generator to make Bokeh scatter plot with categorical values

我想使用循环作为生成器来创建单独的字形以生成散点图。我的 x 值是分类值。我从以下简单示例开始。

from bokeh.plotting import figure, show

xvals = ['one', 'two', 'three']
p = figure(x_range=xvals)

i=1
for value in xvals:
   p.circle(x=value,y=i)
   i+=1

show(p)

这导致 Bokeh 抛出错误:

Bokeh Error attempted to retrieve property array for nonexistent field 'one'

我猜这可以通过使用 columndatasource 并将其作为源传递给字形渲染函数来排序。我尝试了各种方法来构建数据并将其传递给渲染器,但没有成功。 columndatasource 对象想要传递一个格式为:

的字典
data = {'x_values': [1, 2, 3, 4, 5],
    'y_values': [6, 7, 2, 3, 6]}

我无法在生成器之前调用完整的 y 值列表,因为它们将在我的真实函数的循环中计算。有没有办法解决?使用 pyplot 非常容易做到这一点,但我需要使用 Bokeh 来绘制交互式图表。

谢谢!

必须使用 ColumnDataSource 对象。这是一种使用 pandas 数据帧实现具有分类 x 值的 y 值生成器的方法。

import pandas
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from random import randrange

xvals = ['one', 'two', 'three', 'four']
yvals = []

#Here is the generator function
for num in xvals:
    yvals.append(randrange(0,10))

#Construct a dataframe from generator function        
df=pandas.DataFrame({'XVals': xvals, 'YVals': yvals})
source = ColumnDataSource(df)

#Create the plot
p = figure(x_range=xvals)
p.circle(x='XVals',y='YVals', source=source)
show(p)