You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将密集分布的样本点绘制为平滑的可视化图像

解决方案

你需要的是2D核密度估计(KDE)可视化,可以直接对散点的分布进行平滑拟合,输出连续的密度图像,完美解决散点边缘模糊的问题。

方法1:使用seaborn.kdeplot(最简单方案)

代码如下:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# 你的原始数据生成代码
x = np.linspace(0,6,500)
y = np.linspace(0,6,500)
X,Y = np.meshgrid(x,y)
s = np.sin(X) + np.cos(Y)
t = np.sin(X) / (np.cos(Y) + 2)
ST = [(s[i,j], t[i,j]) for i in range(s.shape[0]) for j in range(s.shape[1])]
s_arr, t_arr = zip(*ST)

# 绘制平滑密度图
plt.figure(figsize=(8,6))
# fill=True 填充密度区域,cmap可自定义配色,thresh=0 去掉极低密度的边缘留白
sns.kdeplot(x=s_arr, y=t_arr, fill=True, cmap='viridis', thresh=0)
plt.xlabel('s')
plt.ylabel('t')
plt.show()

你可以通过调整bw_adjust参数控制平滑程度,数值越大平滑效果越强。

方法2:2D直方图+高斯滤波(无需额外可视化库依赖,可控性更高)

如果不想引入seaborn,可通过numpy和scipy自行实现平滑:

import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter

# 原始数据生成同上,得到s_arr和t_arr
s_arr, t_arr = zip(*ST)

# 生成2D直方图
hist, xedges, yedges = np.histogram2d(s_arr, t_arr, bins=100)
# 高斯平滑,sigma值越大平滑程度越高
hist_smoothed = gaussian_filter(hist, sigma=2)

# 绘制平滑热力图
plt.figure(figsize=(8,6))
plt.imshow(hist_smoothed.T, origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmap='viridis')
plt.xlabel('s')
plt.ylabel('t')
plt.colorbar(label='点密度')
plt.show()

内容的提问来源于stack exchange,提问作者user3015347

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:36:04