How can i plot the difference between two histograms? (Julia)

Viewed 161

So time ago i asked the same question here and someone answered just what i wanted! Using fit(histogram...) and weights you can do it! (just like the picture below).

julia> using StatsBase, Random; Random.seed!(0);

julia> x1, x2 = rand(100), rand(100);

julia> h1 = fit(Histogram, x1, 0:0.1:1);

julia> h2 = fit(Histogram, x2, 0:0.1:1);

julia> using Plots

julia> p1 = plot(h1, α=0.5, lab="x1") ; plot!(p1, h2, α=0.5, lab="x2")

julia> p2 = bar(0:0.1:1, h2.weights - h1.weights, lab="diff")

julia> plot(p1, p2)

The problem is i can't use fit, i need to use Histogram(...). And this one doesn't have .weights. How can i do this using Histogram ? This is what i'm using:

using Plots
using StatsBase   
h1 = histogram(Group1, bins= B, normalize =:probability, labels = "Group 1")
h2 = histogram(Group2 , bins= B, normalize =:probability, labels ="Group 2"))

enter image description here

1 Answers

Technically there is no Histogram function in any common Julia package; perhaps you mean either the Histogram (capital h) type provided by StatsBase, or the histogram (lowercase h) function provided by Plots.jl? In either case though, the answer is "you can't".

If you mean histogram from Plots.jl there is unfortunately no practical way to access that underlying data. If you mean Histogram from StatsBase on the other hand, that only works with fit (it's a type, not a function that can be used on its own).

There are other histogram packages though if for any reason you cannot or do not want to use StatsBase and fit, including FastHistograms.jl and NaNStatistics.jl, both of which are additionally somewhat faster than StatsBase for simple cases. So, for example

using NaNStatistics, Plots
a,b = rand(100), rand(100)
dx = 0.1
binedges = 0:dx:1
aw = histcounts(a, binedges)
bw = histcounts(b, binedges)
bar(binedges, aw-bw, label="difference", bar_width=dx)

histogram diff example

Related