我有一个使用sns.kdeplot
的密度图(下面的代码)。我想确定KDE图中的minimum
和maximum
值,以确定变量的双峰性。
# code for kde plot
import seaborn as sns
fig = plt.figure(figsize=(8,6))
y = np.array(RZS_P['Mean_Treecover'])
x = np.array(RZS_P['MAP'])
ax = sns.kdeplot(x, y, shade=True, n_levels=1000, cmap = 'Spectral', cbar=True, shade_lowest=False, alpha = 0.6)
ax.set_xlim(0,2500)
ax.set_ylim(0,90)
在单变量设置中确定maximum
和minimum
的值非常容易,但是在双变量设置中我完全忘了(同样,在提取值时也遇到了麻烦(get.values()
)(从seaborn
包中尝试)。有人可以向我提供一些想法来确定这些minimum
和maximum
值吗?
下面显示一个示例。黑白点代表maximum
和minimum
内核密度。
答案:感谢@ JohanC的指导。新代码如下所示:
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
y = np.array(RZS_P['Mean_Treecover'])
x = np.array(RZS_P['MAP'])
xmin, xmax = 0, 2500
ymin, ymax = 0, 100
# Peform the kernel density estimate
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,6))
ax = fig.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# Contourf plot
cfset = ax.contourf(xx, yy, f, cmap='autumn_r',levels = 100)
#plt.colorbar(cfset)
## Or kernel density estimate plot instead of the contourf plot
ax.imshow(np.rot90(f), extent=[xmin, xmax, ymin, ymax], aspect='auto')
# Contour plot
cset = ax.contour(xx, yy, f, colors='k',levels = 100, lw = 0.002, alpha = 0.1)
# Label plot
#ax.clabel(cset, inline=1, fontsize=10)
ax.set_xlabel('Y1')
ax.set_ylabel('Y0')
### Argmin/max calculation
argmax_65 = []
argmax_30 = []
argmin = []
for i in range(100):
if xx[i,0] <= 1750:
argmax_30.append(np.argmax(f[i,:30]))
if xx[i,0] > 1750:
argmax_30.append(np.nan)
if xx[i,0] >= 1000:
argmax_65.append(65+np.argmax(f[i,65:]))
if xx[i,0] < 1000:
argmax_65.append(np.nan)
if (xx[i,0] >= 1000) & (xx[i,0] <= 1750):
argmin.append(30+np.argmin(f[i,30:60]))
else:
argmin.append(np.nan)
###
plt.scatter(np.linspace(xmin,xmax,100), np.array(argmax_65), c = 'black', edgecolor = 'w', s = 70, linewidth='0.75')
plt.scatter(np.linspace(xmin,xmax,100), np.array(argmax_30), c = 'black', edgecolor = 'w', s = 70, linewidth='0.75')
plt.scatter(np.linspace(xmin,xmax,100), np.array(argmin), c = 'w', edgecolor = 'b', s = 70)
plt.ylim(0,90)
plt.show()