What does `density()` do when applied to a `Distribution` directly?

I just started experimenting with Distributions.jl and StatsPlots.jl, and made a basic mistake, writing density(Normal()) instead of density(rand(Normal(), 100_000)) or plot(Normal()). When executing

julia> plot(Normal(), label="plot()")
julia> density!(rand(Normal(), 100_000), label="density(rand())")
julia> density!(Normal(), label="density()")

Here is the result:

image

What is plotted with density ?

It’s strange that density!(Normal(), label="density()") doesn’t throw an error, because StatsPlots.density! is a generic function with 1 method.

?density # or density!

displays that

density(x)
density!(x)

make a line plot of a kernel density estimate of x, where x is an AbstractVector of samples for probability density estimation.
Or you passed a distribution, not a sample from that distribution.

This does seem strange. I’m having a difficult time finding exactly where density is defined in the source code…?

This is a use case for @which:

julia> using Distributions, StatsPlots

julia> plot(Normal(), label="plot()")

julia> density!(rand(Normal(), 100_000), label="density(rand())")

julia> density!(Normal(), label="density()")

julia> @which density!(Normal(), label="density()")
kwcall(::NamedTuple, ::typeof(density!), args...)
     @ Plots ~/.julia/packages/RecipesBase/BRe07/src/RecipesBase.jl:429

That line of code is in this block:

macro shorthands(funcname::Symbol)
    funcname2 = Symbol(funcname, "!")
    quote
        export $funcname, $funcname2
        Core.@__doc__ $funcname(args...; kw...) =
            $RecipesBase.plot(args...; kw..., seriestype = $(Meta.quot(funcname)))
        Core.@__doc__ $funcname2(args...; kw...) =
            $RecipesBase.plot!(args...; kw..., seriestype = $(Meta.quot(funcname)))
    end |> esc
end

It’s a very old issue:

1 Like

It looks like the macro is auto-writing code and this is a special case where it should do something different?

That is my understanding, although it is bit tricky for me to follow: StatsPlots has a lot of explicit calls to that @shorthand macro, but I didn’t see the one for density.