Plot 2D histogram of 3D+ multivariate data

To plot a bivariate histogram with as many bins as I like in each dimension, I can use

using StatsBase, Plots
d1 = randn(10_000)
d2 = randn(10_000)

nbins1 = 25
nbins2 = 10
	
hist = fit(Histogram, (d1,d2),
		(range(minimum(d1), stop=maximum(d1), length=nbins1+1),
		range(minimum(d2), stop=maximum(d2), length=nbins2+1)))
plot(hist)

How can I make a 3D+ histogram object and extract bivariate slices for plotting? The plot step doesn’t work, but is there something similar to the following that would let me plot a bivariate histogram in dims 1 and 3?

d1 = randn(10_000)
d2 = randn(10_000)
d3 = randn(10_000)

nbins1 = 25
nbins2 = 10
nbins3 = 15
	
hist = fit(Histogram, (d1,d2,d3),
		(range(minimum(d1), stop=maximum(d1), length=nbins1+1),
		range(minimum(d2), stop=maximum(d2), length=nbins2+1),
		range(minimum(d3), stop=maximum(d3), length=nbins3+1)))
plot(hist[1,3])
1 Like

The following seems to slice it, but please further QC its correctness:

for j in 1:nbins2
    x = getindex(hist.edges, 3)
    x = (x[1:end-1] + x[2:end])/2
    y = getindex(hist.edges, 1)
    y = (y[1:end-1] + y[2:end])/2
    z = hist.weights[:,j,:]
    display(heatmap(x,y,z, title="(i, j=$j, k)"))
    println("[ENTER] to continue...")
    readline()
end