Levels keyword but for scatter plot

Hi!
The levels keyword of surface is useful:

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

ax, hm = contourf(fig[1, 1], xs, ys, zs,
    colormap = :Spectral, levels = [-1, -0.5, -0.25, 0, 0.25, 0.5, 1])
Colorbar(fig[1, 2], hm)
display(fig)

What I’d like to do is the same but now for a scatterplot where the marker color is the colorbar. Using levels with scatter errors:

fig = Figure()

xs = LinRange(0, 20, 50)

ys = LinRange(0, 15, 50)

zs = [cos(x) * sin(y) for (x,y) in zip(xs, ys)]

ax, hm = scatter(fig[1, 1], xs, ys; color = zs, colormap = :Spectral, levels = [-1, 0, 1])

Colorbar(fig[1, 2], hm)

display(fig)

Not sure about your use case, but here, without levels and using a categorical colormap. I hope it helps.

using CairoMakie, Colors, ColorSchemes
xs = LinRange(0, 20, 20)
ys = LinRange(0, 15, 20)
zs = [cos(x) * sin(y) for (x,y) in zip(xs, ys)]
fig = Figure()
ax, hm = scatter(fig[1, 1], xs, ys; color = zs, markersize = 20,
    colormap= cgrad(:Spectral_11, 3, categorical=true, rev=true),
    colorrange = (-1, 1))
cbar = Colorbar(fig[1, 2], hm, label="Levels")
cbar.ticks = ([-0.66, 0, 0.66], ["-1", "0", "1"])
fig

2 Likes

Yeah, this achieves what I want (besides the ticks not corresponding to real values). I wonder, can we automate it so that scatter! does this automatically given a levels keyword?

Notice: my use case is not a “categorical colormap”. I simply want to reduce the amount of possible colors from the 512 or so (default colormap) to e.g. 11. Reduce the amount of plotted information, but conserve a “continuous” colormap in a sense. Just what levels does for surface pretty much.

Reduce the amount of plotted information, but conserve a “continuous” colormap in a sense

That is what the categorical keyword does - it’s an ordinal color scale, not a nominal one.
It would make sense to fix the color bar ticks though.