更改sns.heatmap中特定标签的颜色?

时间:2020-04-07 13:39:25

标签: python python-3.x seaborn

是否可以更改sns.heatmap中特定标签的颜色?

基于我的尝试on this answer,我尝试了以下操作:

mask = np.zeros_like(cor, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
plt.figure(figsize=(12,10))
g = sns.heatmap(cor,
            vmin=-1,
            cmap='coolwarm',
            annot=False,
            mask = mask);

columns = df.columns
lut = dict(zip(columns, "rbg"))
row_colors = columns.map(lut)

for tick_label in g.ax_heatmap.axes.get_yticklabels():
    tick_text = tick_label.get_text()
    if tick_text == 'ascii':
        column = columns.loc[int(tick_text)]
        tick_label.set_color(lut[column])

但是得到了:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-204-67642fc463ec> in <module>
     12 row_colors = columns.map(lut)
     13 
---> 14 for tick_label in g.ax_heatmap.axes.get_yticklabels():
     15     tick_text = tick_label.get_text()
     16     if tick_text == 'ascii':

AttributeError: 'AxesSubplot' object has no attribute 'ax_heatmap'

还有一个热图,其中ascii标签不是红色。

1 个答案:

答案 0 :(得分:0)

您复制的答案是一个clustermap,它返回一个具有多个轴的对象。

在这里,您正在使用heatmap,它在单个轴上运行。您应该写:

ax = sns.heatmap(cor,
            vmin=-1,
            cmap='coolwarm',
            annot=False,
            mask = mask);
(...)
for tick_label in ax.get_yticklabels():
    (...)