在散景热图中更改标签顺序

Change label ordering in bokeh heatmap

来自散景示例

from bokeh.charts import HeatMap, output_file, show

data = {'fruit': ['apples']*3 + ['bananas']*3 + ['pears']*3,
        'fruit_count': [4, 5, 8, 1, 2, 4, 6, 5, 4],
        'sample': [1, 2, 3]*3}

hm = HeatMap(data, x='fruit', y='sample', values='fruit_count',
             title='Fruits', stat=None)

show(hm)

是否有更改标签显示顺序的解决方法?比如我想先显示pears?

首先,你不应该使用bokeh.charts。它已被弃用,并已从核心 Bokeh 中删除到单独的 bkcharts 存储库。它完全不受支持和维护。它不会看到任何新功能、错误修复、改进或文档。这是一个死胡同。


创建此图表有两个不错的选择:

1) 使用稳定且得到良好支持的 bokeh.plotting API。这有点冗长,但可以让您明确控制一切,例如类别的顺序。在下面的代码中,这些被指定为 x_rangey_range 值到 figure:

from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.palettes import Spectral9
from bokeh.plotting import figure
from bokeh.transform import transform

source = ColumnDataSource(data={
    'fruit': ['apples']*3 + ['bananas']*3 + ['pears']*3,
    'fruit_count': [4, 5, 8, 1, 2, 4, 6, 5, 4],
    'sample': ['1', '2', '3']*3,
})

mapper = LinearColorMapper(palette=Spectral9, low=0, high=8)

p = figure(x_range=['apples', 'bananas', 'pears'], y_range=['1', '2', '3'], 
           title='Fruits')
p.rect(x='fruit', y='sample', width=1, height=1, line_color=None,
       fill_color=transform('fruit_count', mapper), source=source)

show(p)

这会产生以下输出:

您可以在用户指南的 Handling Categorical Data 部分找到更多关于 Bokeh 分类数据的信息(以及实例)。

2) 与 bokeh.charts 一样,查看 HoloViews, which is a very high level API on top of Bokeh that is actively maintained by a team, and endorsed by the Bokeh team as well. A simple HeatMap in HoloViews 通常是一行代码。