Alec
Alec

Reputation: 4482

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

Upvotes: 2

Views: 788

Answers (2)

Dan Getz
Dan Getz

Reputation: 18217

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.

Upvotes: 1

flurble
flurble

Reputation: 1106

You need to map the x-axis of the figure to the color value color=:x. Then use a colormap that has transparency. Here I manually define one using HSLA values (Hue, saturation, lightness, alpha), varying only the alpha value of the colors. colormap=cgrad([HSLA(0,0,0,1), HSLA(0,0,0,.3), HSLA(0,0,0,1)], 3, categorical=true)

This will shade the middle part of your density area in a transparent color. After that it just comes down to fine-tuning the limits of the color transitions. You could, for example, supply the colorrange argument to the plotting call.

In total that makes it:

using CairoMakie, Colors, ColorSchemes

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

density!(ax, randn(200),
    color=:x,
    colormap=cgrad([HSLA(0,0,0,1), HSLA(0,0,0,.3), HSLA(0,0,0,1)], 3, categorical=true),
    colorrange=(your_x_min,your_x_max),
    )

f

enter image description here

Upvotes: 1

Related Questions