colors - 显示与行颜色对应的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()
解决方案
按照文档中的示例,可以创建一个自定义图例:
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')
推荐阅读
- java - 整数引用传递给方法但不改变
- python - 如何使用 startfile 和相对路径在程序中启动另一个文件?
- postgresql - 如何使用 sqlalchemy 在 JSON 列上放置 ForeignKey 约束?
- java - 用于“单读”REST API 的适当 HTTP 方法
- python - AWS Lambda 中退出与返回的使用
- excel - 功能:如何使用偏移量从过滤的单元格创建范围
- javascript - 我想以特定的时间间隔将每个列表项插入 div
- python - 我正在尝试在列表中创建一个列表
- kubernetes - 如何为预签名 URL 设置 minio 域?
- python - 在熊猫数据框中的字符串后添加空格:TypeError:字符串索引必须是整数