Search code examples
plotjuliamakie.jl

In Makie.jl, how to shade range of density plot?


How can I shade the middle 50% of this density plot a different color of blue (or different alpha transparency)?

using CairoMakie

f = Figure()
Axis(f[1, 1])

density!(randn(200))

f

enter image description here


Solution

  • This answer is a development of @flurble's answer which did all the hard bits of finding the right options and parameters. To make it more usable, I've added a helper function, and switched from using a categorical colormap to a continuous one (which is easier to manipulate). The code looks like this:

    using CairoMakie, Colors, ColorSchemes, Random, StatsBase
    
    # generate 'square' color gradient
    in_out_colorscheme(outcolor, incolor, eps=0.00000001) = 
        cgrad([outcolor, incolor, incolor, outcolor], [0.0,eps,1.0-eps,1.0])
    
    out_blue = HSLA(200,0.9,0.8,0.8)
    in_blue = HSLA(200,0.9,0.4,0.8)
    blue_in_blue = in_out_colorscheme(out_blue, in_blue);
    
    # generate some data
    data = begin
        Random.seed!(14)
        randn(200)
    end;
    
    # the region to highlight will be a 50% quantile interval
    your_x_min, your_x_max = quantile(data, (0.25,0.75))
    
    begin
        f = Figure()
        ax = Axis(f[1, 1])
        density!(data,
    #       strokecolor = out_blue, strokewidth = 2, strokearound = true,
            color=:x,
            colormap=blue_in_blue,
            colorrange=(your_x_min,your_x_max)
        )
        f
    end
    

    And the result is:

    Output chart

    PS The weird begin-end blocks originate from Pluto notebook cells this code was written in.