I have points (x,y) coordinates and I plot them and their density using a kde gaussian estimation, now using contourf i have different colors depending on the density but what i'd like to do is to give in the colorbar or on the plot the number of points contained within each 'zones', is there a way to do this ?
Here is my code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
# Generate some random data
x = np.random.rand(100)
y = np.random.rand(100)
# create a figure with two subplots
fig, ax = plt.subplots(2, sharex=True)
# generate 2D grids for the x and y bounds
xcontour = np.linspace(0, np.max(x), len(x))
ycontour = np.linspace(0, np.max(y), len(y))
xv, yv = np.meshgrid(xcontour, ycontour)
positions = np.vstack([xv.ravel(), yv.ravel()])
# compute the kernel density estimate
values = np.vstack([x, y])
kernel = gaussian_kde(values)
f = np.reshape(kernel(positions).T, xv.shape)
# get the contour levels and number of points in each bin
contour = ax[1].contourf(xv, yv, f,cmap='Blues')
hist, _, _ = np.histogram2d(x, y, bins=(xcontour, ycontour))
hist = hist.T
# add text annotations to the contour plot
for i in range(len(xcontour)-1):
for j in range(len(ycontour)-1):
if int(hist[i,j]) > 0:
x_pos = (xcontour[i] + xcontour[i+1])/2
y_pos = (ycontour[j] + ycontour[j+1])/2
ax[1].text(x_pos, y_pos, int(hist[i,j]), ha='center', va='center')
# add a colorbar to the plot
cbar = plt.colorbar(contour, ax=ax[1], shrink=.6)
cbar.ax.set_ylabel('Density')
# set the title of the contour plot
ax[1].set_title('Density of points')
# plot the scatter points
ax[0].scatter(x, y, s=1, marker=',')
# show the plot
plt.show()
I tried different approaches using also histograms but this is not exactly what i want i prefer to use contours.
Bonus question: someone knows why my contour plot does not go up to the same xlim of the top plot ?