Cleb
Cleb

Reputation: 25997

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?

Upvotes: 1

Views: 659

Answers (2)

Kam Sen
Kam Sen

Reputation: 1148

Interestingly, OP's code worked for me. I came here because I had the same problem. Turns out that the annotation data should be a string. After converting the respective column in ColumnDataSource() my annotations (numbers) showed up in the heatmap.

Upvotes: 0

HYRY
HYRY

Reputation: 97281

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.

Upvotes: 1

Related Questions