Labeling a categorical color dimension in 3d scatter in Makie

I’m trying to do a 3D Iris plot in Makie, but I can not figure out how to label the color dimension. Here is what I do:

using DataFrames
using WGLMakie
using RDatasets
using CategoricalArrays

iris = dataset("datasets", "iris")

f = Figure()
ax3 = Axis3(f[1,1])
scatter!(ax3, iris.SepalLength, iris.SepalWidth, iris.PetalLength; color = levelcode.(iris.Species), label = levels(iris.Species))

and this is what I get:

image

This is all good, but I would like a legend showing which Species maps to which color.

Calling axislegend() gives this error:

ERROR: ArgumentError: all component arrays must have the same shape

I get the same error if I give the label argument as string.(iris.Species):

scatter!(ax3, iris.SepalLength, iris.SepalWidth, iris.PetalLength; color = levelcode.(iris.Species), label = string.(iris.Species)) # , colormap = cgrad(:viridis; categorical=true)) string.(iris.Species) levels(iris.Species)

It is probably just a small thing I’m doing wrong, but I was not able to find a good example online to learn from.

Hope somebody here can help.

I found a solution. Posting here for later reference:

using GLMakie
using RDatasets

iris = dataset("datasets", "iris")

function plot3d(df; x_var=:x , y_var=:y, z_var=:z, color_var=:color)
    x_dat = df[:,x_var]
    y_dat = df[:,y_var]
    z_dat = df[:,z_var]
    color_dat = df[:,color_var]
    color_levels = unique(color_dat)
    fig = Figure()
    ax = Axis3(fig[1,1], xlabel = string(x_var), ylabel = string(y_var), zlabel=string(z_var))
    for c in color_levels
        scatter!(ax, x_dat[color_dat .== c], y_dat[color_dat .== c], z_dat[color_dat .== c], label = c)
    end
    axislegend()
    (;fig,ax)
end

fig, ax = plot3d(iris, x_var = :SepalLength, y_var = :SepalWidth, z_var = :PetalLength, color_var = :Species)

fig

billede

1 Like