1

I am trying to cluster data according to the density of the data points.

1

I want to draw contours around these regions according to the density.Like so:

2

I am trying to adapt the following code from here to get to this point:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

# Sort the points by density, so that the densest points are plotted last
idx = z.argsort()
x, y, z = x[idx], y[idx], z[idx]

fig, ax = plt.subplots()
img=ax.scatter(x, y, c=z, edgecolor='')

plt.show()
Community
  • 1
  • 1

1 Answers1

0

To cluster by density, try an algorithm like DBSCAN. However, it looks like you rather want to estimate the density itself and not cluster points together because you want to color your output by density. In that case, use a simple Kernel density estimate (density function in R) or an adaptive kernel density estimate if you have broad and very sharp peaks at the same time. Example for Matlab: Adaptive Kernel density estimate on Matlab File Exchange

akraf
  • 2,965
  • 20
  • 44