Heatmap using categorical colours

I plot a heatmap of as

using CairoMakie
x=[1; 2; 1; 2; 501; 500; 501; 500]
f = Figure()
ax = Axis(f[1,1])
hm = heatmap!(ax, ones(8), 1:8, x, colormap=cgrad(:viridis, 4, categorical=true))
Colorbar(f[:, 2], hm)
f

Can I have a colour for each value in x?

Colormaps are for linear lookup, so it’s easiest for you to transform your data to category indices and then change the labels on the colormap accordingly.

1 Like

Thanks @jules . By category indices you mean something like 1 β†’ 1, 2 β†’ 2, 500 β†’ 3, 501 β†’ 4?

Yes exactly. The colorrange can then be set to min-0.5, max+0.5 so you have one tick in the middle of each color block.

2 Likes