如何为Seaborn Clustermap的行颜色添加对应图例(基于鸢尾花数据集)
给Seaborn Clustermap添加物种颜色图例
没问题,我来帮你搞定这个图例的问题!你的现有代码已经做好了行颜色映射,现在只需要手动添加一个匹配物种与颜色的自定义图例就行,步骤很简单:
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt import matplotlib.patches as mpatches 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) # 为每个物种创建对应的颜色补丁,用于图例 legend_elements = [mpatches.Patch(color=color, label=species_name) for species_name, color in lut.items()] # 将图例添加到图中,调整位置避免遮挡热图 g.ax_row_dendrogram.legend(handles=legend_elements, loc="upper right", bbox_to_anchor=(1.2, 1)) plt.show()
关键步骤解释:
- 导入补丁模块:新增
matplotlib.patches,它能帮我们创建代表每个物种颜色的小方块(补丁),这是自定义图例的基础。 - 生成图例元素:通过列表推导式遍历你定义的
lut字典,把每个物种名称和对应的颜色配对成补丁对象,这样图例就能清晰显示“物种名+对应颜色”的匹配关系。 - 添加并定位图例:我们把图例放在行树状图的右上角,用
bbox_to_anchor参数微调位置,确保它不会挡住热图的内容,同时又醒目易读。
这样修改后,你就能看到每个鸢尾花物种和对应颜色的匹配图例了,完美解决你的需求!
内容的提问来源于stack exchange,提问作者Amilovsky
相关产品推荐
相关产品推荐

