我正在尝试使用 python 的 Bokeh 库对简单的分类热图进行颜色编码。例如,给定下表,我希望将每个“A”替换为红色方 block ,将每个“B”替换为蓝色方 block :
AAAABAAAAB
BBBAAAABBB
首先,我认为下面的代码会生成 2 行,每行 10 个相同颜色的正方形。但我只是得到一个空白的情节。我一定错过了如何在 Bokeh 中创建分类热图的核心概念。首先,我尝试模仿 Bokeh 网站上的一个示例:
https://docs.bokeh.org/en/latest/docs/gallery/categorical.html
有人看到我错过了什么吗? (这是一个简单的示例。我有很多行和数百列,我需要按类别着色。)
from bokeh.plotting import figure, show, output_file
hm = figure()
colors = ['#2765a3' for x in range(20)]
x_input = [x for x in range(10)]
y_input = ['a', 'b']
hm.rect(x_input, y_input, width = 1, height = 1, color = colors)
output_file('test.html)
show(hm)
最佳答案
您需要为每个矩形创建特定坐标。如果 y 轴上有 2 个可能的值,x 轴上有 10 个可能的值,则所有矩形有 20 可能的唯一坐标对(即这两个值的叉积)列表)。例如:
(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), ...
如果将每个元组拆分为 x 坐标和 y 坐标,并将 x 和 y 收集到它们自己的列表中,您就会明白为什么必须同时有 20 个 x 坐标和 20 个 y 坐标。
此外,对于分类坐标,您必须告诉 figure
它们是什么。这是您更新的代码:
from bokeh.plotting import figure, show
colors = ['#2765a3' for x in range(20)]
x = list(range(10)) * 2
y = ['a'] * 10 + ['b'] * 10
hm = figure(y_range=('a', 'b'))
hm.rect(x, y, width=1, height=1, fill_color=colors, line_color="white")
show(hm)
User's Guide section on Categorical Data有关如何在 Bokeh 中使用分类的更多信息,包括 complete examples of heat maps
关于Python 3 Bokeh Heatmap 矩形简单示例未在图中显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47115600/