显示与行颜色对应的 seaborn clustermap 的图例

Ami*_*sky 1 colors legend heatmap seaborn

''' 为简单起见,让我们使用 iris 数据集。我想添加一个将每个物种与其颜色代码匹配的图例(在本例中为蓝色、绿色、红色)。顺便说一句,我在以下链接中发现了类似的问题,但更复杂一些。 如何在 Seaborn 中的热图轴上表达类

Seaborn clustermap row color with legend 中提出的解决方案会起作用,但是对于 df[['tissue type','label']] 在定义 legend_TN 时,我不确定如何类似地定义标签,例如 iris['species' ,'xxxx'] 预先感谢您帮助我。'''

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

iris = sns.load_dataset('iris')
species = iris.pop('species')


lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
g = sns.clustermap(iris, row_colors=row_colors)
plt.show()
Run Code Online (Sandbox Code Playgroud)

Joh*_*anC 5

按照文档中的示例,可以创建一个自定义图例:

from matplotlib.patches import Patch

handles = [Patch(facecolor=lut[name]) for name in lut]
plt.legend(handles, lut, title='Species',
           bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure, loc='upper right')
Run Code Online (Sandbox Code Playgroud)

示例图