I want to use KDE to estimate the cluster density across a list of XY points I have detected in my microscopy images (that's a completely different process). I'm trying to adapt the code in this answer: https://stackoverflow.com/a/64499779/2009558
Why doesn't the output of the KDE map to the input dimensions? I don't get what the need is to map the KDE output to a grid. Nor why the dimensions of the grid don't match input data. What is the value of "128j" in this line?
gx, gy = np.mgrid[x.min():x.max():128j, y.min():y.max():128j]
What sort of python object is that? It's got both numbers and letters, but it's not a string? I tried googling this but couldn't find an answer. Numpy is so unpythonic sometimes, it drives me nuts.
Here's where I'm at so far. The data's just a pandas df with X and Y coordinates as floats.
import numpy as np
import plotly.express as px
import plotly.offline as offline
import pandas as pd
from scipy.stats import gaussian_kde
xx = df['X']
yy = df['Y']
xy = np.vstack((xx, yy))
kde = gaussian_kde(xy)
gx, gy = np.mgrid[xx.min():xx.max():128j, yy.min():yy.max():128j]
gxy = np.dstack((gx, gy))
# print(gxy[0])
z = np.apply_along_axis(kde, 2, gxy)
z = z.reshape(128, 128)
fig = px.imshow(z)
fig.add_trace(go.Scatter(x = xx, y = yy, mode='markers', marker = dict(color='green', size=1)))
fig.show()
This produces most of the plot I want: The density plot with the points overlaid on it, but the dimensions of the density data are 128 x 128, instead of the dimensions of the limits of the input.
When I try substituting the real dimensions in the reshaping like this
z = z.reshape(ceil(xx.max()-xx.min()), ceil(yy.max()-yy.min()))
I just get errors.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19840/2556669395.py in <module>
12 z = np.apply_along_axis(kde, 2, gxy)
13 # z = z.reshape(128, 128)
---> 14 z = z.reshape(ceil(xx.max()-xx.min()), ceil(yy.max()-yy.min()))
15
16 fig = px.imshow(z)
ValueError: cannot reshape array of size 16384 into shape (393,464)