Seaborn KDE图添加units权重遇参数未使用警告问题求助
解决2D加权密度图(KDE/热力图)的权重失效问题
问题原因
Seaborn的kdeplot在2D模式下不支持weights参数,这就是你收到"The following kwargs were not used by contour: 'weights', 'fill'"警告、权重未生效的核心原因——当前版本的Seaborn处理2D KDE时,会直接把weights传给底层的contour绘图函数,但contour并不支持这个参数,导致权重被完全忽略。
可行解决方案
因为你无法通过复制数据放大权重(数据量/权重规模太大),下面提供两种无需复制数据的实现方式:
方案1:手动用Scipy实现加权2D KDE
直接调用Scipy的gaussian_kde(原生支持权重参数),再用Matplotlib绘制结果:
import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.stats import gaussian_kde # 生成模拟数据(替换为你的真实数据) X = np.random.rand(100000) Y = np.random.rand(100000) units = np.random.rand(100000) kde_data = pd.DataFrame({'X': X, 'Y': Y, 'units': units}).dropna() if len(kde_data) < 3: print("Insufficient data to create the density plot.") else: # 提取数据和权重数组 xy = np.vstack([kde_data['X'], kde_data['Y']]) weights = kde_data['units'] # 初始化加权KDE模型 kde = gaussian_kde(xy, weights=weights) # 生成绘图网格 x_grid = np.linspace(kde_data['X'].min(), kde_data['X'].max(), 100) y_grid = np.linspace(kde_data['Y'].min(), kde_data['Y'].max(), 100) X_grid, Y_grid = np.meshgrid(x_grid, y_grid) xy_grid = np.vstack([X_grid.ravel(), Y_grid.ravel()]) # 计算网格点的加权密度值 Z = kde(xy_grid).reshape(X_grid.shape) # 绘制填充等高线图(加权密度图) plt.figure(figsize=(10, 8)) contour = plt.contourf(X_grid, Y_grid, Z, cmap='viridis', levels=20) plt.colorbar(contour, label='Weighted Density') plt.title('Weighted 2D KDE Plot') plt.xlabel('Predicted Value') plt.ylabel('Actual Value') plt.show()
方案2:加权二维热力图(更高效,适合大数据)
如果不需要严格的KDE平滑效果,加权直方图(热力图)是更轻量化的选择,Matplotlib的hist2d原生支持weights参数:
import matplotlib.pyplot as plt import numpy as np import pandas as pd # 生成模拟数据(替换为你的真实数据) X = np.random.rand(100000) Y = np.random.rand(100000) units = np.random.rand(100000) kde_data = pd.DataFrame({'X': X, 'Y': Y, 'units': units}).dropna() if len(kde_data) < 3: print("Insufficient data to create the density plot.") else: plt.figure(figsize=(10, 8)) # 绘制加权二维直方图 counts, x_edges, y_edges, im = plt.hist2d( kde_data['X'], kde_data['Y'], weights=kde_data['units'], bins=50, cmap='viridis', cmin=1e-6 # cmin避免空bin显示异常 ) plt.colorbar(im, label='Weighted Count') plt.title('Weighted 2D Histogram (Heatmap)') plt.xlabel('Predicted Value') plt.ylabel('Actual Value') plt.show()
补充:叠加散点图
如果需要在密度图/热力图上叠加散点图,直接在绘图代码后添加以下语句即可(调整s和alpha避免遮挡密度层):
plt.scatter(kde_data['X'], kde_data['Y'], s=1, alpha=0.1, color='white')
内容的提问来源于stack exchange,提问作者Data of All Kinds
相关产品推荐
相关产品推荐

