jar1
September 2, 2024, 9:38pm
1
How to map a categorical column to a categorical color palette in Makie?
using CairoMakie,AlgebraOfGraphics,RDatasets
diamonds = dataset("ggplot2","diamonds")
In AoG it’s just
data(diamonds) * mapping(:Carat, :Price; color=:Color) * visual(Scatter) |> draw
but how to do it in Makie?
julia> scatter(diamonds.Carat, diamonds.Price; color=string.(diamonds.Color))
ERROR: Unknown color: E
aplavin
September 2, 2024, 9:51pm
2
I thought “surely Categorical
should work”, but surprisingly it doesn’t:
julia> scatter(rand(100), rand(100), color=Categorical(rand("abc", 100)))
ERROR: MethodError: no method matching to_color(::Categorical)
Probably a bug, as this
scatter(Categorical(rand("abc", 100)))
works.
1 Like
jar1
September 2, 2024, 10:05pm
3
If I pass color=
strings it tries to parse them as color names and passing CategoricalArrays.CategoricalVector
fails, but passing numbers makes a plot.
That doesn’t seem like an ideal API in the sense that color names are very different from values to be mapped into colors so I wouldn’t expect them to be accepted by the same kwarg.
julia> scatter(
diamonds.Carat,
diamonds.Price;
color=levelcode.(diamonds.Cut),
colormap=Makie.wong_colors(),
)
Though is it me or is there too much yellow there, maybe it’s somehow treating it as continuous rather than categorical?
A workaround (or maybe the official solution?) is to set the label
keyword to your category/string instead of the color
keyword and use a loop.
EDIT: I misread the question/thread at first, sorry.
A vector of colors passed to colormap
is always interpreted as continuous. We probably need an overload to get Categorical
inputs to color to just work…
2 Likes
The Makie has its own elegant methods only with the help of groupby() function from DataFrames, the following code works:
using CairoMakie, RDatasets, DataFrames
diamonds = dataset(“ggplot2”,“diamonds”)
fig = Figure()
ax = Axis(fig[1,1])
for i in groupby(diamonds, :color)
scatter!(ax, i.carat, i.price, label=unique(i.color))
end
fig[1,2] = Legend(fig, ax, “Color”)