【问题标题】:Change the color for ytick labels in seaborn.clustermap更改 seaborn.clustermap 中 ytick 标签的颜色
【发布时间】:2017-11-14 18:19:21
【问题描述】:

是否可以更改 seaborn.clustermap 中 ytick 标签的颜色?

所以对于seaborn Iris example,可以根据物种设置行颜色并绘制clustermap:

import seaborn as sns
iris = sns.load_dataset("iris")
species = iris.pop("species")
lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
g = sns.clustermap(iris)

并且可以得到绘制的行和行标签之间的1-1对应关系:

g.ax_heatmap.yaxis.get_majorticklabels()

有没有办法使用它来根据 row_colors 重新着色 ytick 标签?

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    我在尝试做同样的事情时发现了这个问题,在进一步查看 @tom 的 this answer 后,我设置了自定义刻度标签。

    您需要通过将刻度标签中的文本映射回颜色字典来为每个单独的刻度指定颜色。

    要访问每个刻度,请访问 g.ax_heatmap.axes.get_yticklabels(),然后使用 get_text() 提取刻度的文本。

    在 Iris 数据集的特定示例中,刻度标签文本是熊猫系列 species 的索引,以收集 species 文本,以便您从需要转换的 lut 字典中恢复颜色索引回int 并使用.loc 提取所需的信息。

    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)
    
    for tick_label in g.ax_heatmap.axes.get_yticklabels():
        tick_text = tick_label.get_text()
        species_name = species.loc[int(tick_text)]
        tick_label.set_color(lut[species_name])
    

    您会注意到树状图的颜色和 y 轴刻度标签的颜色有些“不匹配”(例如 97 和 114),这是由于图形的大小造成的。使用figsize 增加大小可以让您发现隐藏的刻度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-16
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多