Nested axis for heatmap chart

I am trying to create a heatmap chart with nested axis, similar to this one but for heatmaps instead of bar charts.
Here is the code I came up with, but I don’t seem to be able to pass tuples as factors?

from bokeh.layouts import row
from bokeh.plotting import figure, show, output_file
from itertools import product

factors_x = ["A", "B", "C"]
factors_y = [["Category1","1"], ["Category1","2"], ["Category1","3"],["Category2","X"], ["Category2","Y"], ["Category3","?"]]
#it works well if I uncomment the following line
#factors_y=[a[1] for a in factors_y]

x=[a[0] for a in product(factors_x,factors_y)]
y=[a[1] for a in product(factors_x,factors_y)]
values=np.random.uniform(size=(len(x),))
colors=['#%02x%02x%02x' % (255,255-int(255*i),0) for i in values]

hm = figure(title="Categorical Heatmap", tools="hover", toolbar_location=None,
            x_range=factors_x, y_range=factors_y)

hm.rect(x, y, color=colors, width=1, height=1)

show(hm)

Many thanks

Hi ahassaine,

I was able to get your code working by pre-declaring the FactorRange for the y_range with the tuples list.

from bokeh.plotting import figure, show
from bokeh.models import FactorRange
from itertools import product
import numpy as np

factors_x = ["A", "B", "C"]
factors_y = [("Category1", "1"), ("Category1", "2"), ("Category1", "3"),
             ("Category2", "X"), ("Category2", "Y"), ("Category3", "?")]

x = [a[0] for a in product(factors_x, factors_y)]
y = [a[1] for a in product(factors_x, factors_y)]

values = np.random.uniform(size=(len(x),))
colors = ['#%02x%02x%02x' % (255, 255-int(255*i), 0) for i in values]

y_range = FactorRange(factors=factors_y)
hm = figure(title="Categorical Heatmap", tools="hover", toolbar_location=None,
            x_range=factors_x, y_range=y_range)
hm.rect(x, y, color=colors, width=1, height=1)
hm.y_range.group_padding = 0

show(hm)

Note that you’ll also want to set the group_padding to 0, otherwise you’ll have gaps between the cells.

2 Likes

Many thanks for this!