简体   繁体   English

使用matplotlib在散点图中绘制Blob下的热图

[英]Plotting heatmaps under blobs in a scatter plot with matplotlib

I have an Nx2 matrix X and an N-dim vector of labels y . 我有一个Nx2矩阵X和一个标签y的N维矢量。 For instance: 例如:

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()

在此处输入图片说明

In the background of this plot I want to plot two heatmaps, with a colormap that has the point's colour in the zones of high points density, so that the image looks like having a purple and a yellow cloud, each centered at the purple and yellow blobs. 在此图的背景中,我想绘制两个热图,其中一个色图在高点密度区域中具有该点的颜色,因此图像看起来像是紫色和黄色的云,每个都以紫色和黄色为中心斑点。

This has been challenging for me. 这对我来说是一个挑战。 I tried creating a 2D histogram for each blob as shown in this answer, and also created a custom colormap so that the low density areas of the plot are white, and the high density areas are coloured with the blob's colour: 我尝试为每个斑点创建2D直方图,如答案所示,并且还创建了自定义颜色图,以使绘图的低密度区域为白色,而高密度区域则以斑点的颜色进行着色:

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]]

But now I don't know how to plot those heatmaps using imshow. 但是现在我不知道如何使用imshow绘制这些热图。 I also want to make sure that if the blobs overlap, so will the heatmaps so that one heatmap does not cover the other heatmap, but rather there is a combination of the heatmaps colours and intensities in the overlapping region. 我还想确保如果斑点重叠,那么热图也将重叠,以使一个热图不会覆盖另一个热图,而是在重叠区域中结合了热图的颜色和强度。

I really appreciate your help! 非常感谢您的帮助!

You could use seaborn's kdeplot 您可以使用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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM