Makie heatmap legend

I have a heatmap and I want a legend explaining the values of the colors.

let ps = 0:.01:1
    ns=1:1000:5_000_000
    f = Figure()
    ax = Axis(f[1,1]; xgridvisible=true, ygridvisible=true, xminorgridvisible=true, yminorgridvisible=true)
    hm = heatmap!(ax, ns, ps, map(((n,p),) -> n*p*(1-p), Iterators.product(ns, ps)))
    translate!(hm, 0, 0, -100) # move heatmap behind gridlines
    Legend(f[1,2], [hm], ["value"], ; tellwidth=false)
    f
end
ERROR: No child plot elements found in plot of type Heatmap{Tuple{Vector{Float32}, Vector{Float32}, Matrix{Float32}}} but also no `legendelements` method defined.
Stacktrace:
  [1] error(s::String)
    @ Base ./error.jl:35
  [2] legendelements(plot::Heatmap{Tuple{Vector{Float32}, Vector{Float32}, Matrix{Float32}}}, legend::Legend)
    @ Makie ~/.julia/packages/Makie/gAmAB/src/makielayout/blocks/legend.jl:427
  [3] LegendEntry(label::String, contentelement::Heatmap{Tuple{Vector{Float32}, Vector{Float32}, Matrix{Float32}}}, legend::Legend; kwargs::Base.Pairs{Symbol, Union{}, Tuple{}, NamedTuple{(), Tuple{}}})
    @ Makie ~/.julia/packages/Makie/gAmAB/src/makielayout/blocks/legend.jl:330
  [4] LegendEntry
    @ ~/.julia/packages/Makie/gAmAB/src/makielayout/blocks/legend.jl:324 [inlined]
  [5] #1717
    @ ./none:0 [inlined]
  [6] iterate
    @ ./generator.jl:47 [inlined]
  [7] collect(itr::Base.Generator{Base.Iterators.Zip{Tuple{Vector{Heatmap{Tuple{Vector{Float32}, Vector{Float32}, Matrix{Float32}}}}, Vector{String}}}, Makie.var"#1717#1718"{Legend}})
    @ Base ./array.jl:782
  [8] Legend(fig_or_scene::GridPosition, contents::Vector{Heatmap{Tuple{Vector{Float32}, Vector{Float32}, Matrix{Float32}}}}, labels::Vector{String}, title::Nothing; kwargs::Base.Pairs{Symbol, Bool, Tuple{Symbol}, NamedTuple{(:tellwidth,), Tuple{Bool}}})
    @ Makie ~/.julia/packages/Makie/gAmAB/src/makielayout/blocks/legend.jl:479
  [9] kwcall(::NamedTuple{(:tellwidth,), Tuple{Bool}}, ::Type{Legend}, fig_or_scene::GridPosition, contents::Vector{Heatmap{Tuple{Vector{Float32}, Vector{Float32}, Matrix{Float32}}}}, labels::Vector{String})
    @ Makie ~/.julia/packages/Makie/gAmAB/src/makielayout/blocks/legend.jl:467
 [10] top-level scope

Seems to be a continuous variable there, is a Colorbar not working for your usecase? How would the legend look?

1 Like

I forgot it was called a colorbar in this case rather than a legend.

Ah! Then this should work.

let ps = 0:.01:1
    ns=1:1000:5_000_000
    f = Figure()
    ax = Axis(f[1,1]; xgridvisible=true, ygridvisible=true, xminorgridvisible=true, yminorgridvisible=true)
    hm = heatmap!(ax, ns, ps, map(((n,p),) -> n*p*(1-p), Iterators.product(ns, ps)))
    translate!(hm, 0, 0, -100) # move heatmap behind gridlines
    Colorbar(f[1,2], hm ; tellwidth=false)
    f
end
1 Like