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

675 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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).

0
On

Exact fitting depends on the bins you use to plot histogram. It is easiest to create fixed-width bins, then do:

julia> using StatsBase

julia> h = fit(Histogram, data, nbins=20)
Histogram{Int64, 1, Tuple{StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}}}
edges:
  -3.0:0.5:3.5
weights: [4, 12, 46, 98, 143, 204, 196, 137, 101, 32, 23, 3, 1]
closed: left
isdensity: false

julia> plot(h)

julia> plot!(x->length(data)*step(h.edges[1])*pdf(dist, x))