更新:下面的答案在所有主要观点上仍然是正确的,但是从 Bokeh 0.7 开始,API 已经略有变化,变得更加明确。一般来说,像:
rect(...)
应该替换为
p = figure(...)
p.rect(...)
以下是 Les Mis 示例中的相关行,简化为您的案例。让我们来看看:
# A "ColumnDataSource" is like a dict, it maps names to columns of data.
# These names are not special we can call the columns whatever we like.
source = ColumnDataSource(
data=dict(
x = [row['name'] for row in joined],
y = [row['name'] for row in joined],
color = list_of_colors_one_for_each_row,
)
)
# We need a list of the categorical coordinates
names = list(set(row['name'] for row in joined))
# rect takes center coords (x,y) and width and height. We will draw
# one rectangle for each row.
rect('x', 'y', # use the 'x' and 'y' fields from the data source
0.9, 0.9, # use 0.9 for both width and height of each rectangle
color = 'color', # use the 'color' field to set the color
source = source, # use the data source we created above
x_range = names, # sequence of categorical coords for x-axis
y_range = names, # sequence of categorical coords for y-axis
)
几点注意事项:
对于数字数据x_range
,y_range
通常会自动提供。我们必须在这里明确给出它们,因为我们使用的是分类坐标。
您可以按照自己的喜好对名称列表进行排序x_range
,y_range
这是它们在绘图轴上显示的顺序。
我假设您想使用分类坐标。:) 这就是 Les Mes 示例所做的。如果您需要数字坐标,请参阅此答案的底部。
此外,Les Mis 示例稍微复杂一些(它有一个悬停工具),这就是我们手动创建 ColumnDataSource 的原因。如果您只需要一个简单的绘图,您可以跳过自己创建数据源,直接将数据传递给rect
:
names = list(set(row['name'] for row in joined))
rect(names, # x (categorical) coordinate for each rectangle
names, # y (categorical) coordinate for each rectangle
0.9, 0.9, # use 0.9 for both width and height of each rectangle
color = some_colors, # color for each rect
x_range = names, # sequence of categorical coords for x-axis
y_range = names, # sequence of categorical coords for y-axis
)
另一个注意事项:这仅在对角线上绘制矩形,其中 x 和 y 坐标相同。从您的描述中,这似乎是您想要的。但为了完整起见,可以绘制具有不同 x 和 y 坐标的矩形。Les Mis 示例就是这样做的。
最后,也许您实际上并不想要分类轴?如果您只想使用坐标的数字索引,则更简单:
inds = [row['index'] for row in joined]
rect(inds, # x-coordinate for each rectangle
inds, # y-coordinate for each rectangle
0.9, 0.9, # use 0.9 for both width and height of each rectangle
color = some_colors, # color for each rect
)
编辑:这是一个使用数字坐标的完整可运行示例:
from bokeh.plotting import *
output_file("foo.html")
inds = [2, 5, 6, 8, 9]
colors = ["red", "orange", "blue", "green", "#4488aa"]
rect(inds, inds, 1.0, 1.0, color=colors)
show()
这是一个使用与分类坐标相同的值:
from bokeh.plotting import *
output_file("foo.html")
inds = [str(x) for x in [2, 5, 6, 8, 9]]
colors = ["red", "orange", "blue", "green", "#4488aa"]
rect(inds, inds, 1.0, 1.0, color=colors, x_range=inds, y_range=inds)
show()