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

Display legend of seaborn clustermap corresponding to the row colors

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

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

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

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