简体   繁体   中英

How to add annotation to heatmap cells?

This is a follow-up question of this one .

I would like to add text to the cells in the heatmap. I thought I could use LabelSet as described here . However, unfortunately, I don't see any labels when I run the following code:

import pandas as pd

from bokeh.io import show
from bokeh.models import (CategoricalColorMapper, LinearColorMapper,
                          BasicTicker, PrintfTickFormatter, ColorBar,
                          ColumnDataSource, LabelSet)
from bokeh.plotting import figure
from bokeh.palettes import all_palettes
from bokeh.transform import transform

df = pd.DataFrame({
    'row': list('xxxxxxyyyyyyzzzzzz'),
    'column': list('aabbccaabbccaabbcc'),
    'content': ['c1', 'c2', 'c3', 'c1', 'c2', 'c3'] * 3,
    'amount': list('123212123212123212')})

df = df.drop_duplicates(subset=['row', 'column'])

source = ColumnDataSource(df)

rows = df['row'].unique()
columns = df['column'].unique()
content = df['content'].unique()

colors = all_palettes['Viridis'][max(len(content), 3)]
mapper = CategoricalColorMapper(palette=colors, factors=content)

TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"

p = figure(title="My great heatmap",
           x_range=rows, y_range=columns,
           x_axis_location="above", plot_width=600, plot_height=400,
           tools=TOOLS, toolbar_location='below',
           tooltips=[('cell content', '@content'), ('amount', '@amount')])

p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_text_font_size = "5pt"
p.axis.major_label_standoff = 0

p.rect(x="row", y="column", width=1, height=1,
       source=source,
       fill_color=transform('content', mapper))

labels = LabelSet(x='row', y='column', text='content', level='glyph',
                  x_offset=1, y_offset=1, source=source,
                  render_mode='canvas')

p.add_layout(labels)
show(p)

I see the heatmap, but no labels. How can I display the text?

There are five levels: "image, underlay, glyph, annotation, overlay". The level of p.rect is glyph, if you don't set the level argument of LabelSet , the level of it is annotation, which is on top of the level glyph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM