python - 使用 matplotlib 在散点图中的 blob 下绘制热图
问题描述
我有一个 Nx2 矩阵X
和一个 N-dim 向量标签y
。例如:
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=2)
plt.scatter(X[:, 0], X[:, 1], c=y, edgecolor='k')
plt.show()
在此图的背景中,我想绘制两个热图,其中一个颜色图在高点密度区域中具有点的颜色,因此图像看起来像有紫色和黄色的云,每个都以紫色和黄色为中心斑点。
这对我来说很有挑战性。我尝试为每个 blob 创建一个 2D 直方图,如本答案所示,还创建了一个自定义颜色图,以便绘图的低密度区域为白色,而高密度区域使用 blob 的颜色着色:
import numpy as np
import seaborn as sns
from matplotlib.colors import ListedColormap
palette_colors = sns.color_palette("deep")
palette = sns.light_palette(palette_colors[0], input="husl", n_colors=100)
my_cmap = ListedColormap(sns.color_palette(palette).as_hex())
whr1 = np.where(y==0)
whr2 = np.where(y==1)
x1 = X[whr1][:, 0]
y1 = X[whr1][:, 1]
x2 = X[whr2][:, 0]
y2 = X[whr2][:, 1]
heatmap1, xedges1, yedges1 = np.histogram2d(x1, y1, bins=50)
extent1 = [xedges1[0], xedges1[-1], yedges1[0], yedges1[-1]]
heatmap2, xedges2, yedges2 = np.histogram2d(x2, y2, bins=50)
extent2 = [xedges2[0], xedges2[-1], yedges2[0], yedges2[-1]]
但现在我不知道如何使用 imshow 绘制这些热图。我还想确保如果 blob 重叠,热图也会重叠,这样一个热图不会覆盖另一个热图,而是重叠区域中的热图颜色和强度的组合。
我真的很感谢你的帮助!
解决方案
你可以使用seaborn 的 kdeplot
x1,y1 = np.random.normal(loc=0.0, scale=1.0, size=(100,)), np.random.normal(loc=2.0, scale=1.0, size=(100,))
x2,y2 = np.random.normal(loc=2., scale=1.0, size=(100,)), np.random.normal(loc=0.0, scale=1.0, size=(100,))
fig, ax = plt.subplots()
sns.kdeplot(x1,y1, shade=True, shade_lowest=False, alpha=0.5, cbar=False, ax=ax, cmap="Blues")
sns.kdeplot(x2,y2, shade=True, shade_lowest=False, alpha=0.5, cbar=False, ax=ax, cmap="Oranges")
ax.scatter(x1,y1, color="C0")
ax.scatter(x2,y2, color="C1")
推荐阅读
- informatica - 我有一个平面文件日期格式是 mm-dd-yyyy,我需要将其加载到表中。在表中,我的日期列为 yyyy-mm-dd
- flutter - Flutter 中 url_launcher 的问题(我无法启动网站)
- python - 循环遍历电子邮件的数据帧会产生 smtplib.SMTPRecipientsRefused 错误
- java - 如何在此方法中将 createCriteria(已弃用)更改为 CriteriaQuery?
- javascript - 如何使用 JS、Chart.js 和 PHP 计算最佳拟合的非线性线(回归线)?
- ios - 命令 PhaseScriptExecution 失败,退出代码为非零(反应本机 0.64.0,xcode 12.4)
- c++ - 如何根据值比较启用模板?
- javascript - 组件数组过滤器问题
- javascript - fetch() 仅在浏览器中设置 4 个 cookie 中的 1 个
- python - 如何在 Keras 中使用文件夹中的图像作为目标?