为 matplotlib / seaborn 图中的某些单元格添加自定义边框

Add custom border to certain cells in a matplotlib / seaborn plot

现在我正在使用 Seaborn 的 clustermap 生成一些聚类热图 - 到目前为止还不错。

对于特定用例,我需要在特定单元格周围绘制彩色边框。有没有办法做到这一点?或者在 matplotlib 中使用 pcolormesh,或者任何其他方式?

你可以通过叠加 Rectangle patch on the cell that you would want to highlight. Using the example plot from the seaborn docs

import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
g = sns.clustermap(flights)

我们可以通过

突出显示一个单元格
from matplotlib.patches import Rectangle
ax = g.ax_heatmap

ax.add_patch(Rectangle((3, 4), 1, 1, fill=False, edgecolor='blue', lw=3))
plt.show()

这将生成带有突出显示单元格的绘图,如下所示:

请注意,单元格的索引基于 0,原点位于左下方。