Makie density line plot

Can I somehow get a density as a line plot in Makie?

The best I’ve come up with so far is

density(randn(1_000), color = (:red, 0.0), strokearound = true, strokecolor = :blue, strokewidth = 2)

which seems a bit clumsy (setting the actual plot to zero and then adding the line, its color, and width seperately), and doesn’t quite produce what I’m looking for, as it also draws a line on the x-axis.

Is there a more straightforward way to do this?

The line on the x axis is specifically enabled with strokearound = true. I guess we could add a type recipe for the KernelDensity object so that it works with lines as well (that could already be the case actually).

Yes, I thought so, but didn’t see another option to get the line (I guess I want strokeabove).

I’m not sure I understand the second part of your answer - are you saying currently density generates a KernelDensity object and I might be able to somehow call lines(kernel_density_instance) to plot that?

Well strokearound = false will not stroke around, just above :slight_smile:

1 Like

Ah my apologies! I thought I need to set strokearound = true to get any line, and strokecolor only sets its color - it hadn’t occurred to me that just setting strokecolor (or indeed just strokewidth - although that, maybe somewhat surprisingly, produces a black line rather than one with the first color on the current palette) produes the line already!

The other thing I meant was this:


1 Like

Thanks, another good one. So to sum up, there’s either:

x = randn(1_000)

density(x, color = (:red, 0.0), strokecolor = :blue, strokewidth = 2)

pros: uses density function, which makes for clear code; cons: quite verbose as one has to set the fill to zero alpha, and then explicitly set color and strokewidth of the line (which also means color is not automatically picked from palette)



pros: more concise, directly plots a line only with the color picked automatically from current palette; cons: slightly less clear code and kde function is not exported so relies on internals?

Would there be a case for a density(x, type = :line) or similar method that is basically a wrapper around the lines solution?

One can of course import KernelDensity themselves, that would make it less hacky looking.

If your issue is that the line is not color-cycled, you can fix that by setting Density = (cycle = [:strokecolor => :color],) in the theme or just cycle = ... in the density call. The default is [:color => :patchcolor].

One other issue I stumbled on actually with the density solution: because the plot is constructed from an empty area with a line around it, the legend doesn’t show a line for the plot, but rather a box, i.e.:

density(x, color = (:red, 0.0), strokecolor = :blue, strokewidth = 2, label = "Test")


yeah that’s because I overrode it to look similar to other area plots