Python - integrate a two-dimensional kernel density estimate in contour lines

I would like to draw a contour plot of kernel density estimation, where KDE is integrated within each area filled with contour.

As an example, imagine that I am calculating KDE two-dimensional data:

data = np.random.multivariate_normal((0, 0), [[1, 1], [2, 0.7]], 100)
x = data[:, 0]
y = data[:, 1]
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)
xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([x, y])
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)

I know how to draw a KDE outline graph.

fig = plt.figure()
ax = fig.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
cfset = ax.contourf(xx, yy, f, cmap='Blues')
cset = ax.contour(xx, yy, f, colors='k')
plt.show()

However, this contour graph shows what the probability density is in each of the filled areas. Instead, I would like the chart to indicate the overall probability of getting into each filled area.

+4
source share
1 answer

, , "", . , , .

/, .

, , , , ( , ) "", -

ff = f.ravel()
order = np.argsort(ff)
fsorted = ff[order]
F = np.cumsum(fsorted)
# depending on how your density is normalised next line may be superfluous
# also note that this is only correct for equal bins
# and, finally, to be unimpeachably rigorous, this disregards the probability
# mass outside the field of view, so it calculates probability condtional
# on being in the field of view
F /= F[-1]
boundaries = fsorted.searchsorted(levels)
new_levels = F[boundaries]

, , , , , , . , "kwarg"

# make a copy to avoid problems with in-place shuffling
# i.e. overwriting positions whose original values are still to be read out
F[order] = F.copy()
F.shape = f.shape
cset = ax.contour(xx, yy, F, levels=new_levels, colors='k')

,

, , , : cb = fig.colorbar(cfset, ax = ax) values โ€‹โ€‹= cb.values.copy() values โ€‹โ€‹[1: ] - = [: - 1].copy() cb.set_ticklabels () - Laura

+1

Source: https://habr.com/ru/post/1666441/


All Articles