density

density(values; npoints = 200, offset = 0.0, direction = :x)

Plot a kernel density estimate of values. npoints controls the resolution of the estimate, the baseline can be shifted with offset and the direction set to :x or :y. bandwidth and boundary are determined automatically by default.

Statistical weights can be provided via the weights keyword argument.

color is usually set to a single color, but can also be set to :x or :y to color with a gradient. If you use :y when direction = :x (or vice versa), note that only 2-element colormaps can work correctly.

Attributes

Available attributes and their defaults for Plot{Makie.density} are:

  bandwidth     MakieCore.Automatic()
  boundary      MakieCore.Automatic()
  color         RGBA{Float32}(0.0f0,0.0f0,0.0f0,0.6f0)
  colormap      :viridis
  colorrange    MakieCore.Automatic()
  colorscale    identity
  cycle         [:color => :patchcolor]
  direction     :x
  inspectable   true
  linestyle     "nothing"
  npoints       200
  offset        0.0
  strokearound  false
  strokecolor   :black
  strokewidth   0
  weights       MakieCore.Automatic()

Examples

using CairoMakie


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

density!(randn(200))

f

using CairoMakie


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

density!(randn(200), direction = :y, npoints = 10)

f

using CairoMakie


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

density!(randn(200), color = (:red, 0.3),
    strokecolor = :red, strokewidth = 3, strokearound = true)

f

using CairoMakie


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

vectors = [randn(1000) .+ i/2 for i in 0:5]

for (i, vector) in enumerate(vectors)
    density!(vector, offset = -i/4, color = (:slategray, 0.4),
        bandwidth = 0.1)
end

f

Gradients

You can color density plots with gradients by choosing color = :x or :y, depending on the direction attribute.

using CairoMakie


months = ["January", "February", "March", "April",
    "May", "June", "July", "August", "September",
    "October", "November", "December"]

f = Figure()
Axis(f[1, 1], title = "Fictive temperatures",
    yticks = ((1:12) ./ 4,  reverse(months)))

for i in 12:-1:1
    d = density!(randn(200) .- 2sin((i+3)/6*pi), offset = i / 4,
        color = :x, colormap = :thermal, colorrange = (-5, 5),
        strokewidth = 1, strokecolor = :black)
    # this helps with layering in GLMakie
    translate!(d, 0, 0, -0.1i)
end
f

Due to technical limitations, if you color the :vertical dimension (or :horizontal with direction = :y), only a colormap made with just two colors can currently work:

using CairoMakie


f = Figure()
Axis(f[1, 1])
for x in 1:5
    d = density!(x * randn(200) .+ 3x,
        color = :y, colormap = [:darkblue, :gray95])
end
f

Using statistical weights

using CairoMakie, Distributions


N = 100_000
x = rand(Uniform(-2, 2), N)

w = pdf.(Normal(), x)

fig = Figure()
density(fig[1,1], x)
density(fig[1,2], x, weights = w)

fig