python-kde(带等高线_记1)
怎么查看具体的核密度数值呢?
参考如下:
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
import pandas as pd
from sklearn.datasets.samples_generator import make_blobs
#源数据
data = pd.read_csv(r'C:\Users\hasee\Desktop\JISHU\O_17.csv')
n_components = 3
#看点
plt.scatter(data['LONGITUDE'], data['LATITUDE'], s=50)
plt.title(f"Example of a mixture of distributions")
plt.xlabel("x")
plt.ylabel("y")
# 提取x,y
x = data['LONGITUDE']
y = data['LATITUDE']
# Define the borders
deltaX = (max(x) - min(x))/10
deltaY = (max(y) - min(y))/10
xmin = min(x) - deltaX
xmax = max(x) + deltaX
ymin = min(y) - deltaY
ymax = max(y) + deltaY
print(xmin, xmax, ymin, ymax)
# 插值
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)
#建图
fig = plt.figure(figsize=(8,8))
ax = fig.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
cfset = ax.contourf(xx, yy, f, cmap='coolwarm')
ax.imshow(np.rot90(f), cmap='coolwarm', extent=[xmin, xmax, ymin, ymax])
cset = ax.contour(xx, yy, f, colors='k')
ax.clabel(cset, inline=1, fontsize=10)
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.title('2D Gaussian Kernel density estimation')
plt.show()
结果类似这样:
续问:中心点的坐标怎么提取呢?
原文章地址:https://towardsdatascience.com/simple-example-of-2d-density-plots-in-python-83b83b934f67