How to make a 3D histogram of a 2D vector distribution in python / plotly

Viewed 592

So, basically I have a list of 2D vectors in python, and I want to make a 3d visualization of the distribution of this vector, like a surface curve, through plotly. I'll leave a sample of the first 4 components of my vector

[[0.35431211986827776, 0.21438054570807566], [0.35431211986827776, 0.21438054570807566], [0.35431211986827776, 0.21438054570807566], [0.35431211986827776, 0.21438054570807566],

so I used the seaborn.kdeplot() to visualize, giving only the 2D visualization of the KDE:

KDE estimator for bivariate sample

But i wanted a 3D result, like in this bivariate normal distribution plot, where de X and Y axis are a 2d matrix and the z axis the pdf:

enter image description here

I think I just need to find a good pdf estimate for each vector in my list. Is there a way to fit a KDE to my data, in order to obtain this approximated distribution of each vector an then plot the surface?

Many thanks

1 Answers

Here's a way to do that:

x = np.random.normal(5, 10, 100000)
y = np.random.normal(10, 3, 100000)
h = np.histogram2d(x, y, bins=50)

def bin_centers(bins):
    centers = (bins + (bins[1]-bins[0])/2) [:-1]    
    return centers

x_bins_centers = bin_centers(h[1])
y_bins_centers = bin_centers(h[2])

df = pd.DataFrame(h[0], index=x_bins_centers, columns=y_bins_centers)
fig = go.Figure(data=[go.Surface(z=df)])
fig.show()

The result is:

enter image description here

Related