Colarbar: equal-sized color rectangles

How do I create a color bar with the same height for each level?
Default scales rectangles according to the levels.

using CairoMakie

xs = LinRange(0, 20, 50)
ys = LinRange(0, 15, 50)
zs = [cos(x) * sin(y) for x in xs, y in ys]

fig = Figure()

ax, hm = contourf(fig[1, 1], xs, ys, zs,
    colormap = :Spectral, levels = [0, 0.1, 0.2, 0.5, 1])
Colorbar(fig[1, 2], hm, ticks = [0, 0.1, 0.2, 0.5, 1])

save("a.png", fig)

This colorbar syntax should also work in Makie ColorSchemes · Plots

1 Like

Try:

using CairoMakie

xs = LinRange(0, 20, 50)
ys = LinRange(0, 15, 50)
zs = [cos(x) * sin(y) for x in xs, y in ys]

fig = Figure()

ax, hm = contourf(fig[1, 1], xs, ys, zs,
    colormap = :Spectral, levels = [0, 0.1, 0.2, 0.5, 1])

# this line has changed...
Colorbar(fig[1, 2]; colormap = cgrad(:Spectral, 5; categorical=true), limits=(0.0,1.0), ticks = 0.1:0.2:0.9, tickformat= (x->string.([0,0.1,0.3,0.4,1])))

save("a.png", fig)

When passing a contour plot to Colorbar it automatically places the ticks and values according to it - and in this case, not exactly as desired. The call in the above call bypasses this default by calling ColorBar directly and specifying more parameters.

1 Like

Thanks for the advice.
Based on your advice, I was able to do what I wanted to do with the following code.

using CairoMakie

xs = LinRange(0, 20, 50)
ys = LinRange(0, 15, 50)
zs = [cos(x) * sin(y) for x in xs, y in ys]

fig = Figure()

ax, hm = contourf(fig[1, 1], xs, ys, zs,
    colormap = :Spectral, levels = [0, 0.1, 0.2, 0.5, 1])
Colorbar(fig[1, 2]; colormap = cgrad(:Spectral, 4; categorical=true), limits=(0.0,1.0), ticks = 0.0:0.25:1.0, tickformat= (x->string.([0,0.1,0.2,0.5,1])))

save("a.png", fig)

1 Like