需要强制重叠 seaborn 的热图和 kdeplot

Need to force overlapping for seaborn's heatmap and kdeplot

我正在尝试将 seaborn 的热图和 kdeplot 结合在一个图中,但到目前为止结果不是很有希望,因为我找不到使它们重叠的方法。结果,heatmap刚好被挤到了图的左边。

我认为原因是seaborn似乎没有将两个图表中的x轴识别为相同的(见下图),尽管数据点完全相同。唯一的区别是对于 heatmap 我需要旋转它们,而对于 kdeplot 则不需要旋转。

因此,轴数据来自同一个数据集,但形式不同,如下面的代码所示。

数据集示例如下所示:

X           Y       Z
7,75        280     52,73
3,25        340     54,19
5,75        340     53,61
2,5         180     54,67
3           340     53,66
1,75        340     54,81
4,5         380     55,18
4           240     56,49
4,75        380     55,17
4,25        180     55,40
2           420     56,42
2,25        380     54,90

我的代码:

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

f, ax = plt.subplots(figsize=(11, 9), dpi=300)
plt.tick_params(bottom='on')

# dataset is just a pandas frame with data
X1 = dataset.iloc[:, :3].pivot("X", "Y", "Z")
X2 = dataset.iloc[:, :2]

ax = sns.heatmap(X1, cmap="Spectral")
ax.invert_yaxis()

ax2 = plt.twinx()

sns.kdeplot(X2.iloc[:, 1], X2.iloc[:, 0], ax=ax2, zorder=2)
ax.axis('tight')

plt.show()

请帮助我将 kdeplot 放在热图的顶部。理想情况下,我希望我的最终图看起来像这样:

任何提示或提示将不胜感激!

这个问题可能有点难以理解,因为数据集不可能“只是一些数据”。 XY 值需要位于非常规则的网格上。没有 X,Y 组合可以重复,但并非所有值都会出现。然后 kdeplot 会显示 X,Y 的使用值集中在哪里。

这样的数据集可以通过首先为完整网格生成虚拟数据,然后取一个子集来模拟。

现在,seaborn 热图使用分类 X 轴和 Y 轴。这样的轴很难与 kdeplot 对齐。要获得带有数值轴的类似热图,可以使用 ax.pcolor()

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

xs = np.arange(2, 10, 0.25)
ys = np.arange(150, 400, 10)
# first create a dummy dataset over a full grid
dataset = pd.DataFrame({'X': np.repeat(xs, len(ys)),
                        'Y': np.tile(ys, len(xs)),
                        'Z': np.random.uniform(50, 60, len(xs) * len(ys))})
# take a random subset of the rows
dataset = dataset.sample(200)

fig, ax = plt.subplots(figsize=(11, 9), dpi=300)

X1 = dataset.pivot("X", "Y", "Z")
collection = ax.pcolor(X1.columns, X1.index, X1, shading='nearest', cmap="Spectral")
plt.colorbar(collection, ax=ax, pad=0.02)
# default, cut=3, which causes a lot of surrounding whitespace
sns.kdeplot(x=dataset["Y"], y=dataset["X"], cut=1.5, ax=ax)
fig.tight_layout()
plt.show()