Search code examples
juliahistogramdensity-plotjulia-plots

Add density curve to histogram with count y-axis in Julia


I would like to add a density curve to a histogram while keeping the y-axis with count values. The answer on this forum describes how to add a density curve to a histogram but with the probability on the y-axis. Here is the code:

Pkg.add("Plots")
Pkg.add("Distributions")
using Distributions, Plots

dist = Normal(0, 1)
data = rand(dist, 1000)
histogram(data, normalize=true)
plot!(x->pdf(dist, x), xlim=xlims())

Output:

enter image description here

It nicely creates the histogram with a density curve and density y-axis. But I was wondering if anyone knows how to add a density curve to a histogram while keeping the y-axis as count values in Julia?


Solution

  • If you still wish to use automatic binning like in the example in the question, then I've found the following will work:

    plt = histogram(data, normalize=false)
    pre_factor = plt.series_list[1]
    factor = pre_factor.plotattributes[:bar_width][1]
    plot!(x->length(data)*factor*pdf(dist, x), xlim=xlims())
    

    The code just digs out the width of the bars in the histogram to properly scale the pdf.

    Also, you might want to look at charts with 2 y-axes. They do appear in some places, and I don't know how to draw them, but maybe someone else does (or it needs investigation).