我可以在 seaborn 热图上叠加 matplotlib 轮廓吗?

Can I overlay a matplotlib contour over a seaborn heatmap?

我在 seaborn 中绘制了热图,并通过 matplotlib.pyplot 绘制了等高线图。

是否可以将两者叠加?

Seaborn 在底层使用 matplotlib。您可以组合 seaborn 图,就好像它们是由 matplotlib 直接创建的一样。要在同一子图中绘制,应使用相同的 ax。要将热图单元格的中心与等高线对齐,您需要将 0.5 添加到 x 和 y 坐标。

这是一个让您入门的示例:

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

data = gaussian_filter(np.random.randn(20, 40), sigma=2)

fig, ax = plt.subplots(figsize=(15, 5))
sns.heatmap(data=data, cbar_kws={'pad': 0.02}, ax=ax)
ax.contour(np.arange(.5, data.shape[1]), np.arange(.5, data.shape[0]), data, colors='yellow')
plt.show()