首页 > 解决方案 > 显示与行颜色对应的seaborn clustermap的图例

问题描述

''' 为了简单起见,让我们使用 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()

标签: colorsseabornlegendheatmap

解决方案


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

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

示例图


推荐阅读